I'm trying to display a list of objects in a table. I can iterate over each individual item to find it's value (using an for loop or a DisplayTemplate), but how do I abitriarily pick one to display headers for the whole group.
Here's an simplified example:
Model:
<!-- language: lang-cs -->public class ClientViewModel
{
public int Id { get; set; }
public List<ClientDetail> Details { get; set; }
}
public class ClientDetail
{
[Display(Name="Client Number")]
public int ClientNumber { get; set; }
[Display(Name = "Client Forname")]
public string Forname { get; set; }
[Display(Name = "Client Surname")]
public string Surname { get; set; }
}
View
<!-- language: lang-html -->@model MyApp.ViewModel.ClientViewModel
@{ var dummyDetail = Model.Details.FirstOrDefault(); }
<table>
<thead>
<tr>
<th>@Html.DisplayNameFor(model => dummyDetail.ClientNumber)</th>
<th>@Html.DisplayNameFor(model => dummyDetail.Forname)</th>
<th>@Html.DisplayNameFor(model => dummyDetail.Surname)</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Details.Count; i++)
{
<tr>
<td>@Html.DisplayFor(model => model.Details[i].ClientNumber)</td>
<td>@Html.DisplayFor(model => model.Details[i].Forname)</td>
<td>@Html.DisplayFor(model => model.Details[i].Surname)</td>
</tr>
}
</tbody>
</table>
Notice: I'm using var dummyDetail = Model.Details.FirstOrDefault();
to get a single item whose properties I can access in DisplayNameFor
.
-
What would be the best way to access those headers ?
-
Will this break if the collection is null?
-
Should I just replace them with hard coded plain text labels?