如何本地化枚举并使用类似于Html.SelectListFor <T>的东西

jga*_*fin 5 asp.net-mvc enums localization

假设我得到了以下类和枚举:

public class MyModel
{
    [DisplayName("Min egenskap")]
    public MyEnum TheProperty {get;set;}
}

public enum MyEnum
{
  [DisplayName("Inga från Sverige")]
  OneValue,

  [DisplayName("Ett annat värde")]
  AnotherValue
}
Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用,因为DisplayNameAttribute不能在枚举上使用.还有其他可以使用的属性吗?

我想要做的是select使用类似的东西生成一个漂亮的html 标签Html.SelectListFor(m => m.TheProperty).该列表将DisplayNameAttribute在生成期间使用或类似属性.

通缉结果:

<select name="TheProperty">
<option value="OneValue">Inga från Sverige</option>
<option value="AnotherValue" selected="selected">Ett annat värde</option>
</select>
Run Code Online (Sandbox Code Playgroud)

Jay*_*neT 4

如何执行此操作的一个示例是在枚举上使用 [Description] 属性:

public enum DaysOfWeek
{
    [Description("Monday")]
    Monday = 1,

    [Description("Tuesday")]
    Tuesday = 2
}
Run Code Online (Sandbox Code Playgroud)

然后创建这个 EnumerationHelper 类,它允许您获取枚举的 Description 属性:

public static class EnumerationHelper
{
    //Transforms an enumeration description into a string 
    public static string Description<TEnum>(this TEnum enumObject)
    {
        Type type = enumObject.GetType();
        MemberInfo[] memInfo = type.GetMember(enumObject.ToString());

        if(memInfo != null && memInfo.Length > 0)
        {
            DescriptionAttribute[] attributes = (DescriptionAttribute[])memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes.Length > 0)
            {
                return attributes[0].Description;
            }
        }

        return enumObject.ToString();

    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以查询枚举类以获取值和描述,然后构建 SelectList。您必须在此类中引用 EnumerationHelper:

var listOfDaysOfWeek = (from DaysOfWeek d in Enum.GetValues(typeof(DaysOfWeek))
                        select new { ID = d, Description = d.Description() });

viewModel.selectListDaysOfWeek = new SelectList(listOfDaysOfWeek, "ID", "Description");
Run Code Online (Sandbox Code Playgroud)

最后在你看来:

<%: Html.DropDownListFor(m => m.DayOfWeek, Model.DaysOfWeek) %>
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。