关于Enum和DataAnnotation [英] About Enum and DataAnnotation
问题描述
我有这个枚举(Notebook.cs):
I have this Enum (Notebook.cs):
public enum Notebook : byte
{
[Display(Name = "Notebook HP")]
NotebookHP,
[Display(Name = "Notebook Dell")]
NotebookDell
}
此类中的此属性(TIDepartment.cs):
Also this property in my class (TIDepartment.cs):
public Notebook Notebook { get; set; }
它的工作完美,我只有一个问题:
It's working perfectly, I just have one "problem":
我创建了一个EnumDDLFor,它显示了在DisplayAttribute中设置的名称,带有空格,但该对象在DisplayAttribute中没有收到该名称,接收到Enum名称(正确的是),所以我的问题是:
I created an EnumDDLFor and it's showing the name I setted in DisplayAttribute, with spaces, but the object doesn't receive that name in DisplayAttribute, receives the Enum name (what is correct), so my question is:
有没有办法使用DisplayAttribute中配置的空格接收名称?
Is there a way to receive the name with spaces which one I configured in DisplayAttribute?
推荐答案
MVC不会使用枚举上的Display属性(或任何我知道的框架)。您需要创建一个自定义的枚举扩展类:
MVC doesn't make use of the Display attribute on enums (or any framework I'm aware of). You need to create a custom Enum extension class:
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));
编辑:支持本地化
这可能不是最有效的方式,但是应该工作。
This may not be the most efficient way, but SHOULD work.
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;
}
}
在枚举中,密钥和资源类型必须为指定:
On the enum, the key and resource type must be specified:
[Display(Name = "MyResourceKey", ResourceType = typeof(MyResourceFile)]
这篇关于关于Enum和DataAnnotation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!