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
I found the solution.
Usage:
You can create a helper class with a function that use expressions to read the DisplayName and GroupName property of the attribute:
and use that in your razor:
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.