本文介绍了如何在MVC视图中循环使用DataAnnotation的DisplayName?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问 DataAnnotation DisplayName 和类似的 GroupName 然后在MVC视图中循环。例如,让我说我的一个模型属性是这样的

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; }
}

如何循环浏览 DisplayName 其中类似的 GroupName

结果应该这样,

首页


  1. 家庭电话

  2. 家庭地址

Office


  1. 办公电话

  2. 办公地址


推荐答案

我找到了解决方案。 b
$ b

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;
    }

用法:

var Home = GetDisplayNamesGrouped(typeof(Person), "Home");
var Office = GetDisplayNamesGrouped(typeof(Person), "Office");

这篇关于如何在MVC视图中循环使用DataAnnotation的DisplayName?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 23:21