我有一个具有 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; }
}
在我的 View 文件中,我动态地迭代属性:
@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
}
我的目标是稍后过滤掉 View 中不需要的属性,而无需在我决定更改类(通过添加或删除属性)时手动编辑 View 。
最佳答案
使用 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>
}
}
关于c# - Html.DisplayNameFor() 使用动态计算的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66321095/