2012-04-21 69 views
0

我有以下視圖模型:我的枚舉類型的項目都沒有翻譯

public class BudgetTypeSiteRowListViewModel 
{ 
    public virtual int BudgetTypeSiteID { get; set; } 
    public virtual string SiteName { get; set; } 
    public virtual BudgetTypeEnumViewModel SiteType { get; set; }   
} 

具有以下枚舉:

public enum BudgetTypeEnumViewModel 
{ 
    [Display(Name = "BudgetTypeDaily", ResourceType = typeof (UserResource))] Daily = 1, 
    [Display(Name = "BudgetTypeRevision", ResourceType = typeof (UserResource))] Revision = 2 
} 

以及列出我的項目如下觀點:

@model IEnumerable<BudgetTypeSiteRowListViewModel> 

<table> 
    @foreach (var item in Model) 
    { 
     <tr> 
      <td>@Html.DisplayFor(m => item.SiteName)</td> 
      <td>@Html.DisplayFor(m => item.SiteType)</td> 
     </tr> 
    } 
</table> 

問題是我列出的項目不在正確的文化。我有'每日'或'修正',我應該有'新聞工作者'或'Dagelijkse'或'Révision'或'Revisie'。

如何在正確的文化中提供我的SiteType(由我的枚舉提供)?

謝謝。

回答

0

你必須編寫使用反射來獲取你的財產

public static string DisplayAttribute<TEnum>(this TEnum enumValue) where TEnum : struct 
{ 
    //You can't use a type constraints on the special class Enum. So I use this workaround 
    if (!typeof(TEnum).IsEnum) 
    throw new ArgumentException("TEnum must be of type System.Enum"); 

    Type type = typeof(TEnum); 
    MemberInfo[] memberInfo = type.GetMember(enumValue.ToString()); 
    if (memberInfo != null && memberInfo.Length > 0) 
    { 
    object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false); 
    if (attrs != null && attrs.Length > 0) 
     return ((DisplayAttribute)attrs[0]).GetName(); 
    } 
    return enumValue.ToString(); 
} 

的enume類型從視圖擴展方法,你會得到個值這樣

@Html.DisplayFor(m => item.SiteType.DisplayAttribute()) 

我希望它能幫助

+0

哇,它的效果很好。謝謝! – Bronzato 2012-04-21 17:48:30