how to use enum with DescriptionAttribute in asp.net mvc

前端 未结 4 1512
故里飘歌
故里飘歌 2021-02-07 06:02

I am new to asp.net MVC. I am trying to use dropdown control on my view page, which populates from enum. I also want to add custom descriptions to dropdown values. I searched so

4条回答
  •  萌比男神i
    2021-02-07 06:38

    I created a helper class that tries different types of attributes. I needed it because I was using bootstrap with https://github.com/civicsource/enums and https://silviomoreto.github.io/bootstrap-select/

    public static class EnumHelper
        {
            static EnumHelper()
            {
                var enumType = typeof(T);
                if (!enumType.IsEnum) { throw new ArgumentException("Type '" + enumType.Name + "' is not an enum"); }
            }
    
            public static string GetEnumDescription(T value)
            {
                var fi = typeof(T).GetField(value.ToString());
                var attributes = (DescriptionAttribute[]) fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                return attributes.Length > 0 ? attributes[0].Description : value.ToString();
            }
    
            public static IEnumerable GetSelectList()
            {
                var groupDictionary = new Dictionary();
    
                var enumType = typeof(T);
                var fields = from field in enumType.GetFields()
                             where field.IsLiteral
                             select field;
    
                foreach (var field in fields)
                {
                    var display = field.GetCustomAttribute(false);
                    var description = field.GetCustomAttribute(false);
                    var group = field.GetCustomAttribute(false);
    
                    var text = display?.GetName() ?? display?.GetShortName() ?? display?.GetDescription() ?? display?.GetPrompt() ?? description?.Description ?? field.Name;
                    var value = field.Name;
                    var groupName = display?.GetGroupName() ?? group?.Category ?? string.Empty;
                    if (!groupDictionary.ContainsKey(groupName)) { groupDictionary.Add(groupName, new SelectListGroup { Name = groupName }); }
    
                    yield return new SelectListItem
                    {
                        Text = text,
                        Value = value,
                        Group = groupDictionary[groupName],
                    };
                }
            }
        }
    

    And you call it like:

    @Html.LabelFor(model => model.Address.State, htmlAttributes: new { @class = "control-label col-md-2" })
    @Html.DropDownListFor(model => model.Address.State, EnumHelper.GetSelectList(), new { @class = "selectpicker show-menu-arrow", data_live_search = "true" }) @Html.ValidationMessageFor(model => model.Address.State, "", new { @class = "text-danger" })

提交回复
热议问题