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

后端 未结 30 1867
不知归路
不知归路 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 16:41

    Well I'm really late to the party, but for what it is worth, I have blogged about this very subject whereby I create a EnumHelper class that enables very easy transformation.

    http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23

    In your controller:

    //If you don't have an enum value use the type
    ViewBag.DropDownList = EnumHelper.SelectListFor();
    
    //If you do have an enum value use the value (the value will be marked as selected)    
    ViewBag.DropDownList = EnumHelper.SelectListFor(MyEnum.MyEnumValue);
    

    In your View:

    @Html.DropDownList("DropDownList")
    @* OR *@
    @Html.DropDownListFor(m => m.Property, ViewBag.DropDownList as SelectList, null)
    

    The helper class:

    public static class EnumHelper
    {
        // Get the value of the description attribute if the   
        // enum has one, otherwise use the value.  
        public static string GetDescription(this TEnum value)
        {
            var fi = value.GetType().GetField(value.ToString());
    
            if (fi != null)
            {
                var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
    
                if (attributes.Length > 0)
                {
                    return attributes[0].Description;
                }
            }
    
            return value.ToString();
        }
    
        /// 
        /// Build a select list for an enum
        /// 
        public static SelectList SelectListFor() where T : struct
        {
            Type t = typeof(T);
            return !t.IsEnum ? null
                             : new SelectList(BuildSelectListItems(t), "Value", "Text");
        }
    
        /// 
        /// Build a select list for an enum with a particular value selected 
        /// 
        public static SelectList SelectListFor(T selected) where T : struct
        {
            Type t = typeof(T);
            return !t.IsEnum ? null
                             : new SelectList(BuildSelectListItems(t), "Text", "Value", selected.ToString());
        }
    
        private static IEnumerable BuildSelectListItems(Type t)
        {
            return Enum.GetValues(t)
                       .Cast()
                       .Select(e => new SelectListItem { Value = e.ToString(), Text = e.GetDescription() });
        }
    }
    

提交回复
热议问题