How to show DisplayName and value of each property in a model dynamically

In some cases, when the properties are more than usual, it is painful to copy and drive some code after another to show all the properties of the model. Therefore, I want to know if there is a way to show all the properties of the 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; }

Now I want to show both the DisplayName and the Value of this model in a 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 />
}
+4
source share
2 answers

You can get the display name and value for each of the following properties:

@using System.ComponentModel.DataAnnotations
@using System.Reflection

@foreach (var item in Model.GetType().GetProperties())
{
        var label = item.GetCustomAttribute<DisplayAttribute>().GetName();
        var value = item.GetValue(Model);
        <div class="row">
            <p class="label">@label</p>
            <p class="value">@value</p>
        </div>
        <br />
        <br />
}
+5
source

I think you should use helpers @Html.EditorForModel()and @Html.DisplayForModel(). You can read about them here .

temlate, .

html , , EditorTemplates DisplayTemplates, HTML UIHint, View for .

@Html.DisplayForModel(),

+1

Source: https://habr.com/ru/post/1598171/


All Articles