I want to access DataAnnotation
’s DisplayName
and similar GroupName
of a model class then loop through in MVC view. For Example let me say one of my model properties are like this
public class Person
{
[Display(Name="Home Phone",GroupName="Home")]
public string HomePhone { get; set; }
[Display(Name = "Home Address", GroupName = "Home")]
public string HomeAddress { get; set; }
[Display(Name = "Office Phone", GroupName = "Office")]
public string OfficePhone { get; set; }
[Display(Name = "Office Address", GroupName = "Office")]
public string OfficeAddress { get; set; }
}
How can I loop through the DisplayName
where similar GroupName
?
The result should like this,
Home
- Home Phone
- Home Address
Office
- Office Phone
- Office Address
You can create a helper class with a function that use expressions to read the DisplayName and GroupName property of the attribute:
public static string GetDisplayName<T, TProp>(Expression<Func<T, TProp>> expression)
{
MemberExpression body = GetMemberExpression(expression);
DisplayNameAttribute attribute = body.Member.GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().Single();
return attribute.DisplayName;
}
and use that in your razor:
<span>@ReflectionHelper.GetDisplayName((Person p) => p.HomePhone)</span>
For readability I recommend you prepare a dictionary (or another model) in your controller using this helper based on your Person class and render that dictionary (or other model) in your view instead of using the helper in razor.
I found the solution.
public List<string> GetDisplayNamesGrouped(Type ClassName, string GroupName)
{
List<string> DisplayNameList = new List<string>();
var properties = ClassName.GetProperties();
foreach (var property in properties)
{
var displayAttribute = property.GetCustomAttributes(typeof(DisplayAttribute), true).FirstOrDefault() as DisplayAttribute;
string displayName = property.Name;
if (displayAttribute != null)
{
if (displayAttribute.GroupName == GroupName)
{
displayName = displayAttribute.Name;
DisplayNameList.Add(displayName);
}
}
}
return DisplayNameList;
}
Usage:
var Home = GetDisplayNamesGrouped(typeof(Person), "Home");
var Office = GetDisplayNamesGrouped(typeof(Person), "Office");