[英]Html.DisplayNameFor() using dynamically calculated 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; }
}
在我的視圖文件中,我正在動態地遍歷屬性:
@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
中。 我需要做的是 output 每個屬性的Display
。 類似於 javascript 通過[]
尋址對象屬性的方式。 IE:
<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
參數值的 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.