Asp.Net MVC3 - How create Dynamic DropDownList

前端 未结 2 1192
甜味超标
甜味超标 2021-02-05 20:54

I found many articles on this but still I don´t know how exactly to do this. I am trying to create my own blog engine, I have View for create article (I am using EF and Code fir

2条回答
  •  醉酒成梦
    2021-02-05 21:32

    Your model seems quite strange. It contains properties such as CategoryID and Category which seem redundant. It also contains a SelectListItem collection property called Categories. So, is this a model or a view model? It looks quite messed up. Let's assume it's a model. In this case it would more likely look something like this:

    public class Article
    {
        public int ArticleID { get; set; }
    
        [Required]
        public string Title { get; set; }
    
        public DateTime Date { get; set; }
    
        [Required()]
        [DataType(DataType.MultilineText)]
        [AllowHtml]
        public string Text { get; set; }
    
        public virtual Category Category { get; set; }
    
        public IEnumerable Categories { get; set; }
    
        public virtual ICollection Comments { get; set; }
    }
    
    public class Category
    {
        public int CategoryID { get; set; }
    
        [Required]
        public string Name { get; set; }
    
        public virtual ICollection
    Articles { get; set; } }

    Now that the model is clear we could define a view model which will be passed to the view. A view model is a class which is specifically designed for the view. So depending on what you intend to put in this view you define it in this view model. So far you have talked only about a drop down, so let's do it:

    public class ArticleViewModel
    {
        public int SelectedCategoryId { get; set; }
        public IEnumerable Categories { get; set; }
    }
    

    and then we have a controller:

    public class ArticlesController: Controller
    {
        private readonly IArticlesRepository _repository;
        public ArticlesController(IArticlesRepository repository)
        {
            _repository = repository;
        }
    
        public ActionResult Index()
        {
            Article article = _repository.GetArticle();
            ArticleViewModel viewModel = Mapper.Map(article);
            return View(viewModel);
        }
    }
    

    So the controller uses a repository to fetch the model, maps it to a view model (in this example I use AutoMapper) and passes the view model to the view which will take care of showing it:

    @model AppName.Models.ArticleViewModel
    @using (Html.BeginForm())
    {
        @Html.DropDownListFor(
            x => x.SelectedCategoryId, 
            new SelectList(Model.Categories, "Value", "Text"),
            "-- Select category --"
        )
        
    }
    

提交回复
热议问题