如何在模型中动态显示DisplayName和每个属性的值
问题描述:
在某些情况下,当属性比平时更多时,很难复制并粘贴一些代码以显示Model的所有属性,因此我想知道有没有一种方法可以动态显示Model的所有属性. 例如,我们有以下TestModel:
In some cases when properties is more than usual it is painful to copy and past some code after another to show all properties of a Model , So I want to know is there a way to show all properties of a Model dynamically. for example, we have this TestModel:
TestModel.cs
[Display(Name = "نام")]
[Required]
public string Name { get; set; }
[Display(Name = "ایمیل")]
[Required]
public string Email { get; set; }
[Display(Name = "شماره تماس")]
[Required]
public string PhoneNumber { get; set; }
现在我想用剃刀同时显示此模型的DisplayName和Value,例如:
Now I want to show both DisplayName and Value of this Model in razor, for example sth like this:
TestRazor.cshtml
@foreach (var Item in Model.GetType().GetProperties())
{
<div class="row">
<p class="label">@Item.DisplayName</p>
<p class="value">@Item.Value</p>
</div>
<br />
<br />
}
答
您可以像这样获得每个属性的显示名称和值:
You can get the display name and value of each property like this:
@using System.ComponentModel.DataAnnotations
@using System.Reflection
@foreach (var item in Model.GetType().GetProperties())
{
var label = item.GetCustomAttribute<DisplayAttribute>().Name;
var value = item.GetValue(Model);
<div class="row">
<p class="label">@label</p>
<p class="value">@value</p>
</div>
<br />
<br />
}