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個員額,並試圖提出解決方案:
- How to get DisplayAttribute of a property by Reflection?
- C# Buddy Classes/Meta Data and Reflection
- Get [DisplayName] attribute of a property in strongly-typed way
但沒有他們可以獲取屬性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;
}
我刪除了我的答案,因爲我怕我帶領你走向錯誤的路線。你可以發佈代碼顯示你如何嘗試檢索'Name'屬性? – 2011-04-27 10:45:44
@Sergi Papaseit:好的,沒問題;)我用我用來檢索屬性值的方法代碼更新了我的問題。謝謝您的幫助! – jmpcm 2011-04-27 10:53:59