2

I have this Model with a lot of properties

public class Task {
    public string Key { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    ....
}

I need to create a table in the View to list all the properties of the Task.

The same question was already asked but I don't want to use ViewData: Looping through view Model properties in a View

Any idea?

Sergio
  • 250
  • 1
  • 4
  • 18

4 Answers4

3

Does this work for you?

@foreach(var task in Model) {
    <tr>
    @foreach(var property in typeof(Task).GetProperties()) {
        <th>@(property.GetValue(task, null))</th>
    }
    </tr>
}
Steve Cooper
  • 20,542
  • 15
  • 71
  • 88
1

You probably need to use reflection to get the properties.

Something like this

@model List<Task>
@if(Model.Any())
{
   var propArr = Model.Events[0].GetType().GetProperties();
   foreach (var ev in Model)
   {
      var p = ev.GetType().GetProperties();
      foreach (var propertyInfo in propArr)
      {
         <h4>@propertyInfo.Name</h4>     
         var val = propertyInfo.GetValue(ev, null);
         if (val != null)
         {
             <p>@val</p>
         }
      }        
    }
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
0

Expanded on Steve Coopers Example:


    <table class="table table-bordered table-responsive table-hover">
                        @foreach (var item in Model.a)
                        {
                            <tr>
                               @foreach (var prop in typeof(a).GetProperties())
                               {
                                   <th>@(prop.Name)</th>
                               }
                            </tr>
                            <tr>
                                @foreach (var prop in typeof(a).GetProperties())
                                {
                                    <td>@(prop.GetValue(item, null))</td>
                                }
                            </tr>
                        }
                    </table>

agohil
  • 3
  • 3
-1

please use this

@foreach (var task in Model)
{    
    <tr>

        <td>
          @task.Title 
        </td>

    </tr>
}

and so on for the other properties. Then in your controller u return a list of task like

`return View(your taskList);`
suulisin
  • 1,414
  • 1
  • 10
  • 17