问题描述
我在一个 ViewModelBase
类中有以下辅助方法,该类被其他视图模型继承:
I have the following helper method in a ViewModelBase
class, which is inherited by other view Models:
public string GetEnumName<T>(Enum value)
{
Type enumType = typeof(T);
var enumValue = Enum.GetName(enumType, value);
MemberInfo member = enumType.GetMember(enumValue)[0];
var attrs = member.GetCustomAttributes(typeof(DisplayAttribute), false);
var outString = ((DisplayAttribute)attrs[0]).Name;
if (((DisplayAttribute)attrs[0]).ResourceType != null)
{
outString = ((DisplayAttribute)attrs[0]).GetName();
}
return outString;
}
然后我从这样的视图中调用它:
I then call this from the view like this:
<p>
@{var rel = Model.GetEnumDisplayName<Enums.wheteverEnum>(Model.wheteverEnum); }
@rel
</p>
问题是 - 我可以使用这个方法,这样我就不必告诉它enum
的类型吗?基本上我想为所有 enum
s 做这个:
Question is - can I work this method so I don't have to tell it the type of the enum
? Basically I'd like todo this for all enum
s:
@Model.GetEnumDisplayName(Model.wheteverEnum)
@Model.GetEnumDisplayName(Model.wheteverEnum)
没有typeof
,没有T
,不需要在View中添加对Enums
命名空间的引用...
No typeof
, no T
, no need to add a reference to the Enums
namespace in the View...
可能吗?
推荐答案
您可以简单地移除类型参数并使其成为扩展方法.
You can simply remove the type parameter and make it an extension method.
public static string DisplayName(this Enum value)
{
Type enumType = value.GetType();
var enumValue = Enum.GetName(enumType, value);
MemberInfo member = enumType.GetMember(enumValue)[0];
var attrs = member.GetCustomAttributes(typeof(DisplayAttribute), false);
var outString = ((DisplayAttribute)attrs[0]).Name;
if (((DisplayAttribute)attrs[0]).ResourceType != null)
{
outString = ((DisplayAttribute)attrs[0]).GetName();
}
return outString;
}
@Model.wheteverEnum.DisplayName()
这篇关于MVC.net 在视图中获取枚举显示名称,而无需在视图中引用枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!