2011-04-27 119 views
3

我有一個從EF4生成的部分類,我分配了一個MetadataType以便在ASP.NET MVC3窗體上顯示控件的名稱,並且按預期工作。無法獲取DisplayAttribute名稱

我想使用分配給每個屬性的相同DisplayAttribute來檢索屬性的顯示Name值以用於其他目的。我的課是這樣的:

using Domain.Metadata; 

namespace Domain 
{ 
    [MetadataType(typeof(ClassAMetada))] 
    public partial class ClassA 
    {} 
} 

namespace Domain.Metadata 
{ 
    public class ClassAMetada 
    { 
     [Display(Name = "Property 1 Description", Order = 1)] 
     public Boolean Property1; 

     [Display(Name = "Property 2 Description", Order = 2)] 
     public Boolean Property2; 
    } 
} 

我已經看到了這3個員額,並試圖提出解決方案:

但沒有他們可以獲取屬性Name va略;該屬性未找到,因此是null,所以它返回一個空字符串(第三個問題)或屬性名稱(第一個問題);爲了發現屬性,第二個問題略有改變,但結果也是一個空字符串。

你能幫我這個嗎?非常感謝!

編輯:

這裏是2種方法我使用中檢索的屬性值(包括工作分開)的代碼。兩者非常相似:第一個使用帶有屬性名稱的字符串,另一個使用lamba表達式。

private static string GetDisplayName(Type dataType, string fieldName) 
{ 
    DisplayAttribute attr; 
    attr = (DisplayAttribute)dataType.GetProperty(fieldName).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); 

    if (attr == null) 
    { 
     MetadataTypeAttribute metadataType = (MetadataTypeAttribute)dataType.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault(); 
     if (metadataType != null) 
     { 
      var property = metadataType.MetadataClassType.GetProperty(fieldName); 
      if (property != null) 
      { 
       attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); 
      } 
     } 
    } 
    return (attr != null) ? attr.Name : String.Empty; 
} 


private static string GetPropertyName<T>(Expression<Func<T>> expression) 
{ 
    MemberExpression propertyExpression = (MemberExpression)expression.Body; 
    MemberInfo propertyMember = propertyExpression.Member; 

    Object[] displayAttributes = propertyMember.GetCustomAttributes(typeof(DisplayAttribute), true); 
    if (displayAttributes != null && displayAttributes.Length == 1) 
     return ((DisplayAttribute)displayAttributes[0]).Name; 

    return propertyMember.Name; 
} 
+0

我刪除了我的答案,因爲我怕我帶領你走向錯誤的路線。你可以發佈代碼顯示你如何嘗試檢索'Name'屬性? – 2011-04-27 10:45:44

+0

@Sergi Papaseit:好的,沒問題;)我用我用來檢索屬性值的方法代碼更新了我的問題。謝謝您的幫助! – jmpcm 2011-04-27 10:53:59

回答

1

您是否考慮將顯示名稱放入資源中?比所有這些反射魔術更容易重用。

你可以簡單地做:

[Display(Name = "Property1Name", ResourceType = typeof(Resources), Order = 1)] 
public Boolean Property1; 

並添加Resources.resx文件到您的項目與Property1Name鍵和「財產1所描述」值。當然,您可能必須將默認資源訪問權限從internal設置爲public

後來,在其他地方,你需要這些字符串只需撥打:

string displayName = Domain.Resources.Property1Name;