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



我有一个超过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
}

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

使用LINQ识别包含Display属性的对象并选择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>
}
}

最新更新