Foreach of a Class properties and display in the View

Asked

Viewed 116 times

1

I have a view on Asp.net mvc as follows

var Maquina = Model.ListMaquinas;

@Html.DisplayNameFor(x => Maquina.Property1 )
@Html.DisplayNameFor(x => Maquina.Property2 )
...
@Html.DisplayNameFor(x => Maquina.Property100 )

Everything works fine.

But as I have many fields I decided to make a foreach in the following way:

var Maquinas = Model.ListaMaquinas;

@foreach( System.Reflection.PropertyInfo item in Maquinas.GetType().GetProperties())
{
    @Html.DisplayNameFor(x => Maquinas.GetType().GetProperty(item.Name) )
}

But so Displaynamefor is not working I’m missing at some point? Could someone help me?

  • You are wrong because it is the variable item that you should use and maybe by using reflection.

  • I tried to use it like this: @Html.Displaynamefor(x => @item.Name) but just print Namenamename...

  • It was answered according to the question the answer was useful ?

1 answer

1


An example to clarify your doubt:

Class

public class People
{    
    public int Id { get; set; }        
    public string Name { get; set; }
}

View:

@model WebApplication1.Models.People
@foreach(var property in Model.GetType().GetProperties())
{
    @Html.DisplayName(property.Name) @Html.Display(property.Name)
    <br />
}

whereas:

  • DisplayName will print the text contained in the value of Name
  • Display will print the value of this property relative to the value of Name

Observing: avoid using this as a rule because, reflection often makes your code slower and in some cases makes it also unnecessary, so every care is little.

  • Virgilio thank you so much for the answer and organization of the solution! I tested it here and it worked! But I noticed something: In my model I have the Dataannotations for the name of the fields, but with Displayname they did not appear. About your remark, thank you very much for the tip. This report will be accessed by system administrators only a few times and does not require performance. This will be a report where I will demonstrate several company reports for 12 months side by side.

  • @Accorsi you wanted reflection so you need to do more to get the settings of Dataannotations, edit your question by placing the example of the class and what value should appear

Browser other questions tagged

You are not signed in. Login or sign up in order to post.