Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show DisplayName and value of each property in Model dynamically

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; }

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 />
}
like image 342
vahid kargar Avatar asked Jul 16 '15 07:07

vahid kargar


2 Answers

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 />
}
like image 101
alisabzevari Avatar answered Nov 14 '22 21:11

alisabzevari


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

This helpers generate edit and view temlate that shows all your model properties and attributes by default.

But if you want to change default html that generate this method you can easily create your own EditorTemplates and DisplayTemplates if you want to change HTML for whoule model or use UIHint Attribute if you need to change View for just some properties.

In you case on your view just write @Html.DisplayForModel() and you will get all properties of your model

like image 41
teo van kot Avatar answered Nov 14 '22 21:11

teo van kot