vahid kargar
vahid kargar

Reputation: 794

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

Upvotes: 6

Views: 4568

Answers (2)

alisabzevari
alisabzevari

Reputation: 8126

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

Upvotes: 6

teo van kot
teo van kot

Reputation: 12491

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

Upvotes: 1

Related Questions