How to get SelectList to honor DisplayName annotation with enums?

百般思念 提交于 2019-12-11 05:50:07

问题


I am using enums in my ViewModels to populate a DropDownListFor like this:

@Html.DropDownListFor(model => model.SelectedDropDownValue, 
       new SelectList(Enum.GetValues(typeof(SearchOptions)), SearchOptions.SSN))

This works well. However, I would like to display the DisplayName property of the DisplayNameAttribute that is associated with each value within the enum.

I have search Stackoverflow and seen a number of ways to do this with helpers, extensions, etc. Is it possible to, within a single statement like this, easily tell the SelectList to use the DisplayNameAttribute?

I'm thinking something like:

@Html.DropDownListFor(model => model.SelectedDropDownValue, 
                      new SelectList(Enum.GetValues(typeof(SearchOptions), 
                      "Value", GetDisplayAnnotation()), SearchOptions.SSN))

回答1:


I have written some code that does the same thing except it looks for the DescriptionAttribute.

Modified for your situation it looks like this:

public static string GetDescription(this Enum value)
{
    if (value == null)
        throw new ArgumentNullException("value");        

    var attribute = value.GetType()
        .GetField(value.ToString())
        .GetCustomAttributes(typeof(DisplayNameAttribute), false)
        .Cast<DisplayNameAttribute>()
        .FirstOrDefault();

    return attribute == null ? value.ToString() : attribute.DisplayName;
}

Rather than create a select list and call the @Html.DropDownList in my view, I have created editor and display templates that look a bit like this (Called Enum.cshtml):

var values = Enum.GetValues(enumType)
    .Cast<Enum>()
    .Select(v => new SelectListItem
    {
        Selected = v.Equals(Model),
        Text = v.GetDescription(),
        Value = v.ToString(),
    });

Html.DropDownList("", values)

I then decorate any enum properties in my ViewModels with the UIHint attribute and any enum properties use the above code automatically.

public class MyViewModel
{
    [UIHint("Enum")]
    public MyEnumType MyProperty { get; set; }
}

There are a couple of edge cases to look out for such as handling null values, nullable types and adding a default entry to the drop down but this should give you the bare bones to get started.



来源:https://stackoverflow.com/questions/13499747/how-to-get-selectlist-to-honor-displayname-annotation-with-enums

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!