c# – 关于Enum和DataAnnotation

我有这个枚举(Notebook.cs):
public enum Notebook : byte
{
   [Display(Name = "Notebook HP")]
   NotebookHP,[Display(Name = "Notebook Dell")]
   NotebookDell
}

我班上的这个属性(TIDepartment.cs):

public Notebook Notebook { get; set; }

它工作得很好,我只有一个“问题”:

我创建了一个EnumDDLFor,它显示我在DisplayAttribute中设置的名称,带有空格,但是对象在DisplayAttribute中没有收到该名称,收到Enum名称(正确),所以我的问题是:

有没有办法接收带有我在DisplayAttribute中配置的空格的名称?

解决方法

MVC没有在枚举(或我知道的任何框架)上使用Display属性.您需要创建自定义Enum扩展类:
public static class EnumExtensions
{
    public static string GetDisplayAttributeFrom(this Enum enumValue,Type enumType)
    {
        string displayName = "";
        MemberInfo info = enumType.GetMember(enumValue.ToString()).First();

        if (info != null && info.CustomAttributes.Any())
        {
            DisplayAttribute nameAttr = info.GetCustomAttribute<DisplayAttribute>();
            displayName = nameAttr != null ? nameAttr.Name : enumValue.ToString();
        }
        else
        {
            displayName = enumValue.ToString();
        }
        return displayName;
    }
}

然后你可以像这样使用它:

Notebook n = Notebook.NotebookHP;
String displayName = n.GetDisplayAttributeFrom(typeof(Notebook));

编辑:支持本地化

这可能不是最有效的方式,但应该工作.

public static class EnumExtensions
{
    public static string GetDisplayAttributeFrom(this Enum enumValue,Type enumType)
    {
        string displayName = "";
        MemberInfo info = enumType.GetMember(enumValue.ToString()).First();

        if (info != null && info.CustomAttributes.Any())
        {
            DisplayAttribute nameAttr = info.GetCustomAttribute<DisplayAttribute>();

            if(nameAttr != null) 
            {
                // Check for localization
                if(nameAttr.ResourceType != null && nameAttr.Name != null)
                {
                    // I recommend not newing this up every time for performance
                    // but rather use a global instance or pass one in
                    var manager = new ResourceManager(nameAttr.ResourceType);
                    displayName = manager.GetString(nameAttr.Name)
                }
                else if (nameAttr.Name != null)
                {
                    displayName = nameAttr != null ? nameAttr.Name : enumValue.ToString();
                }
            }
        }
        else
        {
            displayName = enumValue.ToString();
        }
        return displayName;
    }
}

在枚举上,必须指定密钥和资源类型:

[Display(Name = "MyResourceKey",ResourceType = typeof(MyResourceFile)]

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...