如何使 MVC3 DisplayFor 显示枚举的显示属性的值? [英] How to make MVC3 DisplayFor show the value of an Enum's Display-Attribute?

查看:16
本文介绍了如何使 MVC3 DisplayFor 显示枚举的显示属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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() 显示来自 Display-Attribute 的字符串,而不是仅显示枚举的值名称?(它应该显示未定义"或全彩色",但显示未定义"或全彩色").

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").

感谢您的提示!

推荐答案

自定义显示模板可能会有所帮助(~/Views/Shared/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆