The key point mentioned in the comment is you need System.Reflection to extract the DisplayAttribute
.
Implement an extension method to extract the value from DisplayAttribute
.
public static class ReflectionExtensions
{
public static string ToName(this PropertyInfo propertyInfo)
{
try
{
object[] attributes = propertyInfo.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes != null && attributes.Any())
return ((DisplayAttribute)attributes[0]).Name;
return propertyInfo.Name;
}
catch
{
return propertyInfo.Name;
}
}
}
I wrote a similar implementation in GitHub.
With the below way to iterate all properties in class and get the value of DisplayAttribute
.
Caller
PropertyInfo[] props = typeof(Model).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty);
foreach (PropertyInfo prop in props)
{
string displayName = prop.ToName();
}
Another approach to work with System.Linq.Expression.
public static class ReflectionExtensions
{
public static string ToNameByExpression<T, P>(Expression<Func<T, P>> propertyExpression) where T : new ()
{
MemberExpression expression = propertyExpression.Body as MemberExpression;
if (expression == null)
return null;
return (expression.Member as PropertyInfo)
.ToName();
}
}
Provide the expression to specify the property that you want.
Caller
string displayName = ReflectionExtensions.ToNameByExpression((Model m) => m.FromDate);
Demo @ .NET Fiddle