Search code examples
c#asp.net-mvcrazormodelviewdata

Loop through Model property with Razor in MVC View


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?


Solution

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