2013-06-04 95 views
1

這是我一直在玩的東西。在HTML頁面中顯示時獲取類的顯示屬性

我有這樣的課;

public partial class DespatchRoster : DespatchRosterCompare, IGuidedNav 
{ 
    public string despatchDay { get; set; } 
} 

我已經爲它添加了元數據。

[MetadataType(typeof(RosterMetadata))] 
public partial class DespatchRoster 
{ 
} 

public class RosterMetadata 
{ 
    [Display(Name="Slappy")] 
    public string despatchDay { get; set; } 
}  

在我的HTML我有以下;

<% PropertyInfo[] currentFields = typeof(DespatchRoster).GetProperties(); %> 

<% foreach (PropertyInfo propertyInfo in currentFields){ %> 
    <li class="<%= propertyInfo.Name %>"><%= propertyInfo.Name %></li> 
<%} %> 

我想看到的是Slappy作爲LI而不是despatchDay。

我知道我以前做過這個,但想不到如何。

回答

0

試試這個:

var properties = typeof(DespatchRoster).GetProperties() 
    .Where(p => p.IsDefined(typeof(DisplayAttribute), false)) 
    .Select(p => new 
     { 
      PropertyName = p.Name, p.GetCustomAttributes(typeof(DisplayAttribute),false) 
          .Cast<DisplayAttribute>().Single().Name 
     }); 
+1

沒有得到結果 – griegs

1

嘗試使用由this下面提到的一個。

private string GetMetaDisplayName(PropertyInfo property) 
    { 
     var atts = property.DeclaringType.GetCustomAttributes(
      typeof(MetadataTypeAttribute), true); 
     if (atts.Length == 0) 
      return null; 

     var metaAttr = atts[0] as MetadataTypeAttribute; 
     var metaProperty = 
      metaAttr.MetadataClassType.GetProperty(property.Name); 
     if (metaProperty == null) 
      return null; 
     return GetAttributeDisplayName(metaProperty); 
    } 

    private string GetAttributeDisplayName(PropertyInfo property) 
    { 
     var atts = property.GetCustomAttributes(
      typeof(DisplayNameAttribute), true); 
     if (atts.Length == 0) 
      return null; 
     return (atts[0] as DisplayNameAttribute).DisplayName; 
    } 
0

試試這個:

既然你正在訪問的「正常」 MVC驗證或顯示模板外的元數據,你需要自己註冊TypeDescription

[MetadataType(typeof(RosterMetadata))] 
public partial class DespatchRoster 
{ 
    static DespatchRoster() { 
     TypeDescriptor.AddProviderTransparent(
      new AssociatedMetadataTypeTypeDescriptionProvider(typeof(DespatchRoster), typeof(RosterMetadata)), typeof(DespatchRoster)); 
    } 
} 

public class RosterMetadata 
{ 
    [Display(Name="Slappy")] 
    public string despatchDay { get; set; } 
} 

然後訪問我們需要使用TypeDescriptor不能正常PropertyInfo方法枚舉屬性的顯示名稱。

<% PropertyDescriptorCollection currentFields = TypeDescriptor.GetProperties(typeof(DespatchRoster)); %> 

<% foreach (PropertyDescriptor pd in currentFields){ %> 
    <% string name = pd.Attributes.OfType<DisplayAttribute>().Select(da => da.Name).FirstOrDefault(); %> 
    <li class="<%= name %>"><%= name %></li> 
<%} %>