How to loop through DataAnnotation’s DisplayName i

2019-06-12 15:44发布

问题:

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

  1. Home Phone
  2. Home Address

Office

  1. Office Phone
  2. Office Address

回答1:

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.



回答2:

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");