2012-04-21 59 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