How do you create a dropdownlist from an enum in ASP.NET MVC?

后端 未结 30 1914
不知归路
不知归路 2020-11-21 16:36

I\'m trying to use the Html.DropDownList extension method but can\'t figure out how to use it with an enumeration.

Let\'s say I have an enumeration like

30条回答
  •  悲哀的现实
    2020-11-21 17:04

    This is version for Razor:

    @{
        var itemTypesList = new List();
        itemTypesList.AddRange(Enum.GetValues(typeof(ItemTypes)).Cast().Select(
                    (item, index) => new SelectListItem
                    {
                        Text = item.ToString(),
                        Value = (index).ToString(),
                        Selected = Model.ItemTypeId == index
                    }).ToList());
     }
    
    
    @Html.DropDownList("ItemTypeId", itemTypesList)
    

提交回复
热议问题