Asp.Net MVC3 - How create Dynamic DropDownList

前端 未结 2 1187
甜味超标
甜味超标 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:44

    I have gone through this as well and I have to agree that at first it seems odd (In my explanation I'm assuming you want to select one category only, but the process is very similar for a multi select).

    Basically you need to perform 3 steps:

    1:
    You need two properties on your viewmodel One will hold the selected category id (required for postback) and the other will a SelectList with all possible categories:

    public class Article
    {
        public int ArticleID { get; set; }
    
        public int CategoryID { get; set; }
    
        public SelectList Categories { get; set; }
    }
    

    2:
    Also before passing the viewmodel on to the view you need to initialize the SelectList (Best practivce is to prepare as much as possible before passing a model into the view):

    new SelectList(allCategories, "CategoryID", "Name", selectedCategoryID)
    

    3:
    In the view you need to add a ListBox for the CategoryID property, but using the Categories property too fill the ListBox with values:

    @Html.ListBoxFor(model => model.CategoryID , Model.Categories)
    

    Thats it! In the post back action of the controller you will have the CategoryID set. You can do whatever you need to from there to persist things in your db.

提交回复
热议问题