簡體   English   中英

Html.DisplayNameFor() 使用動態計算的屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM