C# 使用动态计算属性的Html.DisplayNameFor()
我有一个拥有30多个属性的类对象C# 使用动态计算属性的Html.DisplayNameFor(),c#,asp.net-mvc,system.reflection,C#,Asp.net Mvc,System.reflection,我有一个拥有30多个属性的类对象 public class Person { [Display(Name = "A")] public string PropertyA { get; set; } [Display(Name = "B")] public string PropertyB { get; set; } [Display(Name = "C")] public st
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>
这就是我所尝试的:
@foreach(var prop in Model.GetType().GetProperties())
{
<div>@Html.DisplayNameFor(prop.Name)</div> //does not work
}
@foreach(Model.GetType().GetProperties()中的var prop)
{
@Html.DisplayNameFor(prop.Name)//不起作用
}
我的目标是在以后过滤掉视图中不需要的属性,而不必在我决定更改类(通过添加或删除属性)时手动编辑视图。使用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>
}
}
@foreach(Model.GetType().GetProperties()中的var prop)
{
//TODO:决定属性是否应包含在输出中的逻辑
foreach(属性CustomAttributes中的变量ca)
{
var name=ca.NamedArguments.Where(t=>t.MemberName.Equals(“name”))。选择(x=>x.TypedValue.Value)。FirstOrDefault().ToString();
@Html.DisplayName(名称)
}
}
@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>
}
}