加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-05-23 18:22:50 所属栏目:asp.Net 来源:互联网
导读:在MVC3项目中,我正在使用带有display-Attributes的枚举: public enum Foo { [Display(Name = Undefined)] Undef = 0, [Display(Name = Fully colored)] Full = 1} 模型类有一个使用此枚举的属性: public Foo FooProp { get; set; }

在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
        }
    }
}

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读