Reputation: 8341
I am able to get a simple text list of all the property names in a specified class using the following code.
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties();
foreach (var item in propertyInfos)
{
yield return item.Name.ToString();
}
But I have not been able to figure out how to get the Display Name for each field. The display name being designated with the data attribute:
[Display(Name = "First Name")]
public string FirstName { get; set; }
Is there a way using reflection? Or some other way to do it programatically?
Upvotes: 2
Views: 443
Reputation: 7706
You can get CustomAttribute by type in this way:
DisplayAttribute attribute = (DisplayAttribute)item.GetCustomAttribute(typeof(DisplayAttribute));
Now you can get any value of DisplayAttribute fields just using for example
attributes.Name
Upvotes: 4