我有这个枚举 (Notebook.cs):
public enum Notebook : byte
{
[Display(Name = "Notebook HP")]
NotebookHP,
[Display(Name = "Notebook Dell")]
NotebookDell
}
还有我类(class)的这个属性(TIDepartment.cs):
public Notebook Notebook { get; set; }
它工作得很好,我只有一个“问题”:
我创建了一个 EnumDDLFor,它显示了我在 DisplayAttribute 中设置的带有空格的名称,但是该对象在 DisplayAttribute 中没有收到该名称,而是收到了 Enum 名称(正确的是什么),所以我的问题是:
有没有办法接收我在 DisplayAttribute 中配置的带空格的名称?
最佳答案
MVC 不使用枚举的 Display 属性(或我知道的任何框架)。您需要创建自定义枚举扩展类:
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)]
关于c# - 关于 Enum 和 DataAnnotation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30467519/