2014-11-01 191 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