【问题标题】:How to make MVC3 DisplayFor show the value of an Enum's Display-Attribute?如何使 MVC3 DisplayFor 显示枚举的显示属性的值?
【发布时间】:2011-09-08 20:38:05
【问题描述】:

在 MVC3 项目中,我使用带有显示属性的枚举:

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 的字符串,而不是仅显示枚举的值名称? (它应该显示“未定义”或“全彩色”,但显示“未定义”或“全色”)。

感谢您的提示!

【问题讨论】:

    标签: asp.net-mvc-3 attributes enums


    【解决方案1】:

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

    【讨论】:

    • 认为应该是 'if(display.Name.Length > 0)'。 DisplayAttribute 没有属性 Length。
    • FirstOrDefault() 可以返回 NULL(不存在属性),因此您也必须检查!
    • 可以是通用枚举类型模板吗?
    【解决方案2】:

    另一种解决方案

    注意:此代码依赖@Html.DisplayFor()

    我是这样做的……

    using System;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Reflection;
    
    namespace Nilhoor.Utility.Extensions
    {
        public static class EnumExtensions
        {
            .
            .
            .
    
            public static string GetDisplayName(this Enum @enum)
            {
                var memberName = @enum.ToString();
                
                var nameAttribute = @enum.GetType().GetMember(memberName).FirstOrDefault()?.GetCustomAttribute<DisplayAttribute>();
                
                return nameAttribute != null 
                    ? nameAttribute.GetName() 
                    : memberName;
            }
        }
    }
    

    在 x.cshtml 中

    @using Nilhoor.Utility.Extensions
    .
    .
    .
    <span>Value: </span>
    <span>@Model.Type.GetDisplayName()</span>
    

    【讨论】:

      猜你喜欢
      • 2017-04-21
      • 1970-01-01
      • 2014-09-24
      • 2015-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2011-10-22
      相关资源
      最近更新 更多