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

后端 未结 30 1911
不知归路
不知归路 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:03

    In ASP.NET MVC 5.1, they added the EnumDropDownListFor() helper, so no need for custom extensions:

    Model:

    public enum MyEnum
    {
        [Display(Name = "First Value - desc..")]
        FirstValue,
        [Display(Name = "Second Value - desc...")]
        SecondValue
    }
    

    View:

    @Html.EnumDropDownListFor(model => model.MyEnum)
    

    Using Tag Helper (ASP.NET MVC 6):

    <select asp-for="@Model.SelectedValue" asp-items="Html.GetEnumSelectList<MyEnum>()">
    
    0 讨论(0)
  • 2020-11-21 17:03

    Another fix to this extension method - the current version didn't select the enum's current value. I fixed the last line:

    public static SelectList ToSelectList<TEnum>(this TEnum enumObj) where TEnum : struct
        {
            if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
    
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                           select new
                           {
                               ID = (int)Enum.Parse(typeof(TEnum), e.ToString()),
                               Name = e.ToString()
                           };
    
    
            return new SelectList(values, "ID", "Name", ((int)Enum.Parse(typeof(TEnum), enumObj.ToString())).ToString());
        }
    
    0 讨论(0)
  • 2020-11-21 17:03

    You can also use my custom HtmlHelpers in Griffin.MvcContrib. The following code:

    @Html2.CheckBoxesFor(model => model.InputType) <br />
    @Html2.RadioButtonsFor(model => model.InputType) <br />
    @Html2.DropdownFor(model => model.InputType) <br />
    

    Generates:

    enter image description here

    https://github.com/jgauffin/griffin.mvccontrib

    0 讨论(0)
  • 2020-11-21 17:04

    This is version for Razor:

    @{
        var itemTypesList = new List<SelectListItem>();
        itemTypesList.AddRange(Enum.GetValues(typeof(ItemTypes)).Cast<ItemTypes>().Select(
                    (item, index) => new SelectListItem
                    {
                        Text = item.ToString(),
                        Value = (index).ToString(),
                        Selected = Model.ItemTypeId == index
                    }).ToList());
     }
    
    
    @Html.DropDownList("ItemTypeId", itemTypesList)
    
    0 讨论(0)
  • 2020-11-21 17:04
    @Html.DropdownListFor(model=model->Gender,new List<SelectListItem>
    {
     new ListItem{Text="Male",Value="Male"},
     new ListItem{Text="Female",Value="Female"},
     new ListItem{Text="--- Select -----",Value="-----Select ----"}
    }
    )
    
    0 讨论(0)
  • 2020-11-21 17:05

    This is Rune & Prise answers altered to use the Enum int value as the ID.

    Sample Enum:

    public enum ItemTypes
    {
        Movie = 1,
        Game = 2,
        Book = 3
    }
    

    Extension method:

        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                         select new { Id = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };
    
            return new SelectList(values, "Id", "Name", (int)Enum.Parse(typeof(TEnum), enumObj.ToString()));
        }
    

    Sample of usage:

     <%=  Html.DropDownList("MyEnumList", ItemTypes.Game.ToSelectList()) %>
    

    Remember to Import the namespace containing the Extension method

    <%@ Import Namespace="MyNamespace.LocationOfExtensionMethod" %>
    

    Sample of generated HTML:

    <select id="MyEnumList" name="MyEnumList">
        <option value="1">Movie</option>
        <option selected="selected" value="2">Game</option>
        <option value="3">Book </option>
    </select>
    

    Note that the item that you use to call the ToSelectList on is the selected item.

    0 讨论(0)
提交回复
热议问题