2012-02-17 52 views
23

我有一个ViewModelBase类,它是由其它视图模型继承了以下辅助方法:MVC.net GET枚举显示名称中视图,而不必指枚举类型鉴于

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; 
     } 

我然后调用这从这样的观点:

<p> 
@{var rel = Model.GetEnumDisplayName<Enums.wheteverEnum>(Model.wheteverEnum); } 
@rel 
</p> 

的问题是 - 我可以工作,这个方法,所以我没有告诉它enum的类型?基本上,我想这待办事项所有enum S:

@ Model.GetEnumDisplayName(Model.wheteverEnum)

没有typeof,没有T,无需参考在视图中添加到Enums命名空间...

可能吗?

回答

54

你可以简单地删除该类型参数,使其扩展方法。

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() 
+0

+1非常好的。它使用的原始代码加上添加的代码实现的扩展方法,包括如何调用它。 – Nope 2012-02-17 13:44:54

+2

对于c为了完整起见,你应该添加一个检查,如果没有任何''DisplayAttributes'应用于枚举值并返回'value.ToString()'作为默认值。否则,当你调用'((DisplayAttribute)attrs [0])时,你会得到一个'IndexOutOfRangeException'.Name' – flipchart 2013-07-16 09:31:43

+0

如果有人试图从控制器调用:DisplayName((MyEnum)id); – 2013-10-02 08:40:24

7

难道你不能把它写成扩展方法吗?喜欢的东西...

public static class EnumExtensions 
{ 
    public static string ToDescription(this Enum e) 
    { 
    var attributes = (DisplayAttribute[])e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DisplayAttribute), false); 
    return attributes.Length > 0 ? attributes[0].Description : string.Empty; 
    } 
} 

用法:

@Model.WhateverEnum.ToDescription(); 
0

这里是我写的一个扩展方法来做这件事......它有一点额外的逻辑来解析枚举名称和大写字母拆分。您可以通过使用显示属性

public static TAttribute GetAttribute<TAttribute>(this ICustomAttributeProvider parameterInfo) where TAttribute : Attribute 
{ 
    object[] attributes = parameterInfo.GetCustomAttributes(typeof(TAttribute), false); 
    return attributes.Length > 0 ? (TAttribute)attributes[0] : null; 
} 
public static bool HasAttribute<TAttribute>(this ICustomAttributeProvider parameterInfo) where TAttribute : Attribute 
{ 
    object[] attributes = parameterInfo.GetCustomAttributes(typeof(TAttribute), false); 
    return attributes.Length > 0 ? true : false; 
} 

public static string ToFriendlyEnum(this Enum type) 
{ 
    return type.GetType().HasAttribute<DescriptionAttribute>() ? type.GetType().GetAttribute<DescriptionAttribute>().Description : type.ToString().ToFriendlyEnum(); 
} 

public static string ToFriendlyEnum(this string value) 
{ 
    char[] chars = value.ToCharArray(); 
    string output = string.Empty; 

    for (int i = 0; i < chars.Length; i++) 
    { 
     if (i <= 0 || chars[i - 1].ToString() != chars[i - 1].ToString().ToUpper() && chars[i].ToString() != chars[i].ToString().ToLower()) 
     { 
      output += " "; 
     } 

     output += chars[i]; 
    } 

    return output.Trim(); 
} 

getAttribute方法扩展方法可能会稍微矫枉过正覆盖任何名字,但我在我的项目在其他地方使用它们,所以当我写我的枚举扩展他们得到了重用。您可以轻松地将它们组合成ToFriendlyEnum(此枚举类型)方法

5

好的工作@ jrummell!

我添加了一个小的调整,下面捕获其中一个枚举不具有关联显示属性的情况下(目前它抛出一个异常)

/// <summary> 
/// Gets the DataAnnotation DisplayName attribute for a given enum (for displaying enums values nicely to users) 
/// </summary> 
/// <param name="value">Enum value to get display for</param> 
/// <returns>Pretty version of enum (if there is one)</returns> 
/// <remarks> 
/// Inspired by : 
///  http://stackoverflow.com/questions/9328972/mvc-net-get-enum-display-name-in-view-without-having-to-refer-to-enum-type-in-vi 
/// </remarks> 
public static string DisplayFor(this Enum value) { 
    Type enumType = value.GetType(); 
    var enumValue = Enum.GetName(enumType, value); 
    MemberInfo member = enumType.GetMember(enumValue)[0]; 
    string outString = ""; 

    var attrs = member.GetCustomAttributes(typeof(DisplayAttribute), false); 
    if (attrs.Any()) { 
     var displayAttr = ((DisplayAttribute)attrs[0]); 

     outString = displayAttr.Name; 

     if (displayAttr.ResourceType != null) { 
      outString = displayAttr.GetName(); 
     } 
    } else { 
     outString = value.ToString(); 
    } 

    return outString; 
} 
0

的建议sollutions不适合工作我与MVC3:所以帮手下面是很好。:

public static string GetEnumDescription(this Enum value) 
    { 
     Type type = value.GetType(); 
     string name = Enum.GetName(type, value); 
     if (name != null) 
     { 
      FieldInfo field = type.GetField(name); 
      if (field != null) 
      { 
       string attr = field.GetCustomAttributesData()[0].NamedArguments[0].TypedValue.Value.ToString(); 
       if (attr == null) 
       { 
        return name; 
       } 
       else 
       { 
        return attr; 
       } 
      } 
     } 
     return null; 
    } 
1

@ jrummell在VB.NET中的答案我们为数不多...

Module ModuleExtension 

    <Extension()> 
    Public Function DisplayName(ByVal value As System.Enum) As String 

     Dim enumType As Type = value.GetType() 
     Dim enumValue = System.Enum.GetName(enumType, value) 
     Dim member As MemberInfo = enumType.GetMember(enumValue)(0) 

     Dim attrs = member.GetCustomAttributes(GetType(DisplayAttribute), False) 
     Dim outString = CType(attrs(0), DisplayAttribute).Name 

     If (CType(attrs(0), DisplayAttribute).ResourceType IsNot Nothing) Then 
      outString = CType(attrs(0), DisplayAttribute).GetName() 
     End If 

     Return outString 
    End Function 


End Module 
1

的人谁可能会达到这个问题,我发现这个有很多比其他任何事情更容易: https://www.codeproject.com/articles/776908/dealing-with-enum-in-mvc

只需创建下一个文件夹“DisplayTemplate”“查看\共享”,并创建一个空视图(命名为“枚举”)的新文件夹“DisplayTemplate”,而这个代码复制到”

@model Enum 

@if (EnumHelper.IsValidForEnumHelper(ViewData.ModelMetadata)) 
{ 
    // Display Enum using same names (from [Display] attributes) as in editors 
    string displayName = null; 
    foreach (SelectListItem item in EnumHelper.GetSelectList(ViewData.ModelMetadata, (Enum)Model)) 
    { 
     if (item.Selected) 
     { 
      displayName = item.Text ?? item.Value; 
     } 
    } 

    // Handle the unexpected case that nothing is selected 
    if (String.IsNullOrEmpty(displayName)) 
    { 
     if (Model == null) 
     { 
      displayName = String.Empty; 
     } 
     else 
     { 
      displayName = Model.ToString(); 
     } 
    } 

    @Html.DisplayTextFor(model => displayName) 
} 
else 
{ 
    // This Enum type is not supported. Fall back to the text. 
    @Html.DisplayTextFor(model => model) 
}