I have a view that accepts a list of objects.
So, for example, if I had a list of people ... ordered where they were located, and the unit was like this:
| ID | Name | Location | Division | Age |
--------------------------------------------------------------
1 John Building1 Finance 25
2 Alex Building1 Finance 30
3 Chris Building2 ISS 22
4 Justin Building1 Human Resources 41
5 Mary Building2 Accounting 43
6 Ian Building1 Human Resources 27
7 John Building1 Finance 35
So my return action statement looks like this:
lstOfPersonnel = lstOfPersonnel.OrderBy(x => x.Location).ThenBy(x => x.Division).ThenBy(x => x.Name).ToList();
return View(lstOfPersonnel);
In my view, I have the following:
<table class="table table-bordered no-border">
@foreach (var item in Model)
{
if ((Model.IndexOf(item) == 0) || ((Model.IndexOf(item) != 0) && (!item.Building.Equals(Model.ElementAt(Model.IndexOf(item) - 1).Building) || !item.Division.Equals(Model.ElementAt(Model.IndexOf(item) - 1).Division))))
{
<thead>
<tr>
<th><b>@item.Building</b></th>
<th><b>@item.Division</b></th>
</tr>
<tr class="no-display"></tr>
<tr>
<th>Name</th>
</tr>
<tr>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
</tr>
</tbody>
}
else
{
<tbody>
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
</tr>
</tbody>
}
}
</table>
Now, when I print the preview, it puts everyone in the same building and unit under the corresponding heading. However, the very first element <thead>.. allows us to say that for this example there will Building1also be Financedue .OrderBy.... shown on the page each on top of the next building.
So, for visualization, it looks like I'm typing a preview:
Page 1:
// Perfect Render
Building1 | Finance
Name | Age
Alex 30
John 35
John 25
Page 2:
// Repeat of Page 1 headers
Building1 | Finance
Name | Age
Building1 | Human Resources
Name | Age
Ian 27
Justin 41
Page 3:
// Repeat of Page 1 headers
Building1 | Finance
Name | Age
Building2 | Accounting
Name | Age
Mary 43
4:
// Repeat of Page 1 headers
Building1 | Finance
Name | Age
Building2 | ISS
Name | Age
Chris 43