[英]Html.DisplayNameFor() using dynamically calculated properties
I have a class object with more than 30 properties我有一个具有 30 多个属性的 class object
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; }
}
In my view file, I am iterating through the properties dynamically:在我的视图文件中,我正在动态地遍历属性:
@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>
This will list all of the properties, with each property in its own div
.这将列出所有属性,每个属性都在其自己的
div
中。 What I need to do is output the Display
of each property.我需要做的是 output 每个属性的
Display
。 Something like javascript way of addressing an object's properties by []
.类似于 javascript 通过
[]
寻址对象属性的方式。 IE: IE:
<div>@Html.DisplayNameFor(m => m[prop.Name])</div> //does not work
This is what I tried:这是我尝试过的:
@foreach(var prop in Model.GetType().GetProperties())
{
<div>@Html.DisplayNameFor(prop.Name)</div> //does not work
}
My goal is to later filter out properties that are not required in the view, without having to manually edit the view when I decide to alter the class (by adding or removing properties).我的目标是稍后过滤掉视图中不需要的属性,而无需在我决定更改 class(通过添加或删除属性)时手动编辑视图。
Use LINQ to identify an object that contains the Display
attribute and select the Name
argument value:使用 LINQ 来识别包含
Display
属性和 select Name
参数值的 object:
@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>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.