2014-11-01 201 views
0

在我的asp.net MVC5项目中,我正在使用[显示(名称=“字符串”)]注释为枚举,这工作得很好,只要我'米使用:MVC5在@ Html.ActionLink中显示漂亮的显示名称

@Html.DisplayFor(modelItem => item.Category) 

现在,我想在

@Html.ActionLink(item.Category.ToString(), "Category", new { id = item.Category }) 

这当然是这样的用我的漂亮枚举名作为链接文字,但我没有看到DisplayName值(用空格)。我怎样才能做到这一点?

这是我的枚举的样子(只是澄清):

public enum Category 
{ 
    Book, 
    Movie, 
    [Display(Name = "TV Show")] 
    TVShow, 
    [Display(Name = "Video Game")] 
    Videogame, 
    Music, 
    Software, 
    Other 
} 

回答

2
public static class EnumExtension 
{ 
    public static string GetDisplayName(this System.Enum en) 
    { 
     Type type = en.GetType(); 
     MemberInfo[] memInfo = type.GetMember(en.ToString()); 
     if (memInfo != null && memInfo.Length > 0) 
     { 
      object[] attrs = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), true); 
      if (attrs != null && attrs.Length > 0) 
      { 
       return ((DisplayAttribute)attrs[0]).Name; 
      } 
     } 
     return en.ToString(); 
    } 
} 

@Html.ActionLink(item.Category.GetDisplayName(), "Category", new { id = item.Category }) 
+0

我贴你的代码,其中也有我的枚举是我的模型文件。我可以构建代码,但是我在网站上出现了下面的错误:'System.Nullable '没有包含'GetDescription'的定义,它接受'System.Nullable '可以找到。 我在这里错过了什么? – Thomas 2014-11-01 19:16:23

+0

你确定MediaDB.Models.Category是枚举类型吗?从例外看来,你允许将空值作为一个类别。尝试item.Category.Value.GetDescription() - (当然,检查item.Category.HasValue之前)。 请确保您在视图中引用了EnumExtension类。 – free4ride 2014-11-01 20:03:40

+0

谢谢,我错过了@using MediaDB.Models;在视图中的声明。但是,是否可以更改此代码以利用现有的[Display(Name =“TV Show”)]注释,因为我仍然使用这些注释。否则,我必须包含相同的字符串两次。 – Thomas 2014-11-01 20:18:27