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

2

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 />
}
Votaw answered 16/7, 2015 at 7:37 Comment(0)
B
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 />
}
Bastinado answered 16/7, 2015 at 7:59 Comment(3)
compile time error : system.reflection.propertyinfo dos not contain a definition fot GetCustomAttributeVotaw
You need those two namespaces above @using System.ComponentModel.DataAnnotations @using System.ReflectionGrizzled
excuse me, although I pressed right click on error for find resolve option but didnt exist. thank U for your answer @alisabzevari.Votaw
I
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

Impassion answered 16/7, 2015 at 7:49 Comment(4)
No, I escape from using something like @Html.EditorFor(model => model.Name) becouse you mention "Name" , It isnt dynamic as I know.Votaw
Don't you mention that i write EditorForModel not EditorFor editor for Whole model? You don't need to write properties.Impassion
It isnt what I want, please explain more , I cant find my answer in your mentiond website.Votaw
Thank U , answer of @Bastinado is complete I thinkVotaw

© 2022 - 2024 — McMap. All rights reserved.