在MVC3项目中,我正在使用带有display-Attributes的枚举:
- public enum Foo {
- [Display(Name = "Undefined")]
- Undef = 0,[Display(Name = "Fully colored")]
- Full = 1
- }
模型类有一个使用此枚举的属性:
- public Foo FooProp { get; set; }
- @Html.DisplayFor(m => m.FooProp)
现在,最后我的问题:
我如何做.DisplayFor()显示来自Display-Attribute的字符串,而不是仅显示枚举的值名称? (应该显示“未定义”或“全色”,但显示“Undef”或“全部”)。
感谢提示!
解决方法
自定义显示模板可能有帮助(〜/ 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
- }
- }
- }