如何在模型中动态显示DisplayName和每个属性的值 [英] How to show DisplayName and value of each property in Model dynamically
本文介绍了如何在模型中动态显示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 />
}
这篇关于如何在模型中动态显示DisplayName和每个属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文