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

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

    I found an answer here. However, some of my enums have [Description(...)] attribute, so I've modified the code to provide support for that:

        enum Abc
        {
            [Description("Cba")]
            Abc,
    
            Def
        }
    
    
        public static MvcHtmlString EnumDropDownList(this HtmlHelper htmlHelper, string name, TEnum selectedValue)
        {
            IEnumerable values = Enum.GetValues(typeof(TEnum))
                .Cast();
    
            List items = new List();
            foreach (var value in values)
            {
                string text = value.ToString();
    
                var member = typeof(TEnum).GetMember(value.ToString());
                if (member.Count() > 0)
                {
                    var customAttributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (customAttributes.Count() > 0)
                    {
                        text = ((DescriptionAttribute)customAttributes[0]).Description;
                    }
                }
    
                items.Add(new SelectListItem
                {
                    Text = text,
                    Value = value.ToString(),
                    Selected = (value.Equals(selectedValue))
                });
            }
    
            return htmlHelper.DropDownList(
                name,
                items
                );
        }
    

    Hope that helps.

提交回复
热议问题