ASP.NET MVC 4 ViewModel with DropDownList data

后端 未结 4 1862
生来不讨喜
生来不讨喜 2020-12-14 23:35

I\'m using @html.EditorFor to render my model in edit mode, and a dropdownlist is not rendered.

Here\'s my ViewModel:

     public class          


        
4条回答
  •  执念已碎
    2020-12-15 00:03

    binding dropdown list is easy. code as follows

    public ActionResult BindWithModel()
    {
        List items = new List();
    
        items.Add(new SelectListItem 
                    { Text = "Select Category", Value = "0", 
                            Selected = true });
        items.Add(new SelectListItem
                    { Text = "Beverages", Value = "1" });
        items.Add(new SelectListItem
                    { Text = "Condiments", Value = "2" });
        items.Add(new SelectListItem
                    { Text = "Confections", Value = "3" });
        items.Add(new SelectListItem
                    { Text = "Dairy Products", Value = "4" });
        items.Add(new SelectListItem
                    { Text = "Grains/Cereals", Value = "5" });
        items.Add(new SelectListItem
                    { Text = "Meat/Poultry", Value = "6" });
        items.Add(new SelectListItem
                    { Text = "Produce", Value = "7" });
        items.Add(new SelectListItem
                    { Text = "Seafood", Value = "8" });
    
        var model = new CategoryModel()
        {
            lstCategory = items,
            selected = 1
        };
    
        return View(model);
    }
    

    Code in view

    @model BindMvcDropdownList.Models.CategoryModel
    
    

    Bind MVC DropDownList with Model

    @Html.DropDownListFor(x => x.selected, Model.lstCategory)

    code taken from here http://dotnetmentors.com/mvc/how-to-bind-dropdownlist-in-asp-net-mvc-application.aspx

提交回复
热议问题