Good day!
I\'ve such method to get [DisplayName]
attribute value of a property (which is attached directly or using [MetadataType]
attribut
@Buildstarted Answer works but i wanted to get the DisplayName by property name rather using linq expression so i did a little change that will save your time
public static string GetDisplayNameByMemberName(string memberName)
{
Type type = typeof(TModel);
string propertyName = memberName;
DisplayAttribute attr;
attr = (DisplayAttribute)type.GetProperty(propertyName).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault();
//Look for [MetadataType] attribute in type hierarchy
//http://stackoverflow.com/questions/1910532/attribute-isdefined-doesnt-see-attributes-applied-with-metadatatype-class
if (attr == null)
{
MetadataTypeAttribute metadataType = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault();
if (metadataType != null)
{
var property = metadataType.MetadataClassType.GetProperty(propertyName);
if (property != null)
{
attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault();
}
}
}
return (attr != null) ? attr.Name : String.Empty;
}
I also wanted to get the localized value in the resources (.resx files) so :
string displayName = GeneralHelper.GetDisplayNameByMemberName(memberName);
string displayNameTranslated = resourceManager.GetString(displayName, MultiLangHelper.CurrentCultureInfo);
This is a helper function i made to return an object of type "CultureInfo", create a culture info of some language or pass the current one
//MultiLangHelper.CurrentCultureInfo
return System.Threading.Thread.CurrentThread.CurrentCulture;