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

后端 未结 30 1938
不知归路
不知归路 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条回答
  •  梦毁少年i
    2020-11-21 16:57

    For MVC v5.1 use Html.EnumDropDownListFor

    @Html.EnumDropDownListFor(
        x => x.YourEnumField,
        "Select My Type", 
        new { @class = "form-control" })
    

    For MVC v5 use EnumHelper

    @Html.DropDownList("MyType", 
       EnumHelper.GetSelectList(typeof(MyType)) , 
       "Select My Type", 
       new { @class = "form-control" })
    

    For MVC 5 and lower

    I rolled Rune's answer into an extension method:

    namespace MyApp.Common
    {
        public static class MyExtensions{
            public static SelectList ToSelectList(this TEnum enumObj)
                where TEnum : struct, IComparable, IFormattable, IConvertible
            {
                var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                    select new { Id = e, Name = e.ToString() };
                return new SelectList(values, "Id", "Name", enumObj);
            }
        }
    }
    

    This allows you to write:

    ViewData["taskStatus"] = task.Status.ToSelectList();
    

    by using MyApp.Common

提交回复
热议问题