如何使MVC3 DisplayFor显示枚举的显示属性的价值? [英] How to make MVC3 DisplayFor show the value of an Enum's Display-Attribute?
问题描述
在一个MVC3项目,我使用的是枚举带显示的属性:
in a MVC3-Project, I'm using an enum with display-Attributes:
public enum Foo {
[Display(Name = "Undefined")]
Undef = 0,
[Display(Name = "Fully colored")]
Full = 1
}
模型类具有使用此枚举的属性:
The model class has a property using this enum:
public Foo FooProp { get; set; }
该视图使用模型类,并通过
The view uses the model class and displays the property via
@Html.DisplayFor(m => m.FooProp)
现在,终于,我的问题:
Now, finally, my question:
我怎样才能让.DisplayFor()显示从显示属性的字符串,而不是只显示枚举值名称呢? (它应该显示未定义或全彩色,但displaysp未定义或Full)。
How can I make .DisplayFor() show the string from the Display-Attribute instead of showing only the enum's value-name? (it should show "Undefined" or "Fully colored", but displaysp "Undef" or "Full").
谢谢你的提示!
推荐答案
自定义显示模板可以帮助(〜/查看/共享/ DisplayTemplates / Foo.cshtml
):
A custom display template might help (~/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
}
}
}
这篇关于如何使MVC3 DisplayFor显示枚举的显示属性的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!