6

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 />
}
vahid kargar
  • 800
  • 1
  • 9
  • 23

2 Answers2

6

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 />
}
Johan Maes
  • 1,161
  • 13
  • 13
alisabzevari
  • 8,008
  • 6
  • 43
  • 67
  • compile time error : system.reflection.propertyinfo dos not contain a definition fot GetCustomAttribute – vahid kargar Jul 16 '15 at 08:07
  • You need those two namespaces above `@using System.ComponentModel.DataAnnotations` `@using System.Reflection` – Oluwafemi Jul 16 '15 at 08:15
  • excuse me, although I pressed right click on error for find resolve option but didnt exist. thank U for your answer @alisabzevari. – vahid kargar Jul 16 '15 at 08:20
1

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

teo van kot
  • 12,350
  • 10
  • 38
  • 70