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

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

    Here is a better encapsulated solution:

    https://www.spicelogic.com/Blog/enum-dropdownlistfor-asp-net-mvc-5

    Say here is your model:

    enter image description here

    Sample Usage:

    enter image description here

    Generated UI: enter image description here

    And generated HTML

    enter image description here

    The Helper Extension Source Code snap shot:

    enter image description here

    You can download the sample project from the link I provided.

    EDIT: Here's the code:

    public static class EnumEditorHtmlHelper
    {
        /// 
        /// Creates the DropDown List (HTML Select Element) from LINQ 
        /// Expression where the expression returns an Enum type.
        /// 
        /// The type of the model.
        /// The type of the property.
        /// The HTML helper.
        /// The expression.
        /// 
        public static MvcHtmlString DropDownListFor(this HtmlHelper htmlHelper,
            Expression> expression) 
            where TModel : class
        {
            TProperty value = htmlHelper.ViewData.Model == null 
                ? default(TProperty) 
                : expression.Compile()(htmlHelper.ViewData.Model);
            string selected = value == null ? String.Empty : value.ToString();
            return htmlHelper.DropDownListFor(expression, createSelectList(expression.ReturnType, selected));
        }
    
        /// 
        /// Creates the select list.
        /// 
        /// Type of the enum.
        /// The selected item.
        /// 
        private static IEnumerable createSelectList(Type enumType, string selectedItem)
        {
            return (from object item in Enum.GetValues(enumType)
                    let fi = enumType.GetField(item.ToString())
                    let attribute = fi.GetCustomAttributes(typeof (DescriptionAttribute), true).FirstOrDefault()
                    let title = attribute == null ? item.ToString() : ((DescriptionAttribute) attribute).Description
                    select new SelectListItem
                      {
                          Value = item.ToString(), 
                          Text = title, 
                          Selected = selectedItem == item.ToString()
                      }).ToList();
        }
    }
    

提交回复
热议问题