如何使MVC3 DisplayFor显示Enum的显示属性的值?

Sas*_*cha 16 enums attributes asp.net-mvc-3

在MVC3-Project中,我使用带有display-Attributes的枚举:

public enum Foo {
  [Display(Name = "Undefined")]
  Undef = 0,

  [Display(Name = "Fully colored")]
  Full = 1
}
Run Code Online (Sandbox Code Playgroud)

模型类有一个使用此枚举的属性:

public Foo FooProp { get; set; }
Run Code Online (Sandbox Code Playgroud)

视图使用模型类并通过显示属性

@Html.DisplayFor(m => m.FooProp)
Run Code Online (Sandbox Code Playgroud)

现在,最后,我的问题:

我如何使.DisplayFor()显示Display-Attribute中的字符串而不是仅显示枚举的值名称?(它应显示"未定义"或"全彩色",但显示"Undef"或"Full").

谢谢你的提示!

Dar*_*rov 25

自定义显示模板可能有帮助(~/Views/Shared/DisplayTemplates/Foo.cshtml):

@using System.ComponentModel.DataAnnotations
@model Foo

@{
    var field = Model.GetType().GetField(Model.ToString());
    if (field != null)
    {
        var display = ((DisplayAttribute[])field.GetCustomAttributes(typeof(DisplayAttribute), false)).FirstOrDefault();
        if (display != null)
        {
            @display.Name
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 可以是通用枚举类型模板吗? (2认同)