2013-06-04 56 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> 
<%} %>