asp.net-mvc-3 – 如何使MVC3 DisplayFor显示枚举显示属性的值?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 如何使MVC3 DisplayFor显示枚举显示属性的值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在MVC3项目中,我正在使用带有display-Attributes的枚举:
  1. public enum Foo {
  2. [Display(Name = "Undefined")]
  3. Undef = 0,[Display(Name = "Fully colored")]
  4. Full = 1
  5. }

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

  1. public Foo FooProp { get; set; }

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

  1. @Html.DisplayFor(m => m.FooProp)

现在,最后我的问题:

我如何做.DisplayFor()显示来自Display-Attribute的字符串,而不是仅显示枚举的值名称? (应该显示“未定义”或“全色”,但显示“Undef”或“全部”)。

感谢提示

解决方法

自定义显示模板可能有帮助(〜/ Views / Shared / DisplayTemplates / Foo.cshtml):
  1. @using System.ComponentModel.DataAnnotations
  2. @model Foo
  3.  
  4. @{
  5. var field = Model.GetType().GetField(Model.ToString());
  6. if (field != null)
  7. {
  8. var display = ((DisplayAttribute[])field.GetCustomAttributes(typeof(DisplayAttribute),false)).FirstOrDefault();
  9. if (display != null)
  10. {
  11. @display.Name
  12. }
  13. }
  14. }

猜你在找的asp.Net相关文章