How to loop through DataAnnotation’s DisplayName in MVC view?

◇◆丶佛笑我妖孽 提交于 2019-12-08 13:26:48

问题


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


来源:https://stackoverflow.com/questions/28877906/how-to-loop-through-dataannotation-s-displayname-in-mvc-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!