Html.DisplayNameFor() 使用动态计算的属性

Html.DisplayNameFor() using dynamically calculated properties

我有一个 class 对象有超过 30 个属性

public class Person
{
    [Display(Name = "A")]
    public string PropertyA { get; set; }
    
    [Display(Name = "B")]
    public string PropertyB { get; set; }

    [Display(Name = "C")]
    public string PropertyC { get; set; }
    ... 
    ...
    [Display(Name = "Z")]
    public string PropertyZ { get; set; }
}

在我的视图文件中,我正在动态迭代属性:

@model Person

<div>
   @foreach(var prop in Model.GetType().GetProperties())
   {
      // logic to decide if the property should be
       // included in the output or not
      <div>@prop.Name</div>
   }
</div>

这将列出所有属性,每个 属性 在其自己的 div 中。 我需要做的是输出每个属性的Display。 类似于 javascript 通过 [] 寻址对象属性的方式。即:

      <div>@Html.DisplayNameFor(m => m[prop.Name])</div>     //does not work

这是我试过的:

   @foreach(var prop in Model.GetType().GetProperties())
   {

      <div>@Html.DisplayNameFor(prop.Name)</div>             //does not work

   }

我的目标是稍后过滤掉视图中不需要的属性,而无需在我决定更改 class(通过添加或删除属性)时手动编辑视图。

使用 LINQ 识别包含 Display 属性和 select Name 参数值的对象:

@foreach (var prop in Model.GetType().GetProperties())
{
    // TODO: logic to decide if the property should be included in the output or not

    foreach (var ca in prop.CustomAttributes)
    {               
        var name = ca.NamedArguments.Where(t => t.MemberName.Equals("Name")).Select(x => x.TypedValue.Value).FirstOrDefault().ToString();
        <div>@Html.DisplayName(name)</div>
    }
}