What is the cleanest way to render a collection into an html table with "n" number of records per row

I have an asp.net-mvc website. In my view model, I have a collection of cars that I want to display on an HTML table.

I want to show 5 cars per line, so I started something like this:

<table> @foreach (var car in Model.Cars) { if (counter == 0) { <tr> } <td>@car.Name</td> counter++; if (counter == 5) { </tr> } } </table> 

I feel that the code above is a bit hacked, and also, if I have 7 machines, should I put 3 empty <td> in the last line or disable it (again, more hacker code)?

I wanted to know if there was a cleaner way in asp.net-mvc to display a collection in a table with a certain number of records in a table in a row.

+4
source share
2 answers

If you want to stick to the tables, this looks the least dangerous for me.

 @{ var colSize = 5; var rows = (int)(Model.Cars.Count() / colSize); } <table> @for (var row = 0; row <= rows ; row++){ <tr> @foreach(var car in Model.Cars.Skip(row * colSize).Take(colSize)) { <td>@car.Name</td> } </tr> } </table> 

if you want to fill the last line with <td> elements, you can put this before <tr> :

 @if (row == rows) { for(var i=0;i<colSize -( Model.Cars.Count() % colSize); i++){ <td></td> } } 
+4
source

You can do it a little cleaner with something like this:

 <table> <tr> @foreach (var car in Model.Cars) { <td>@car.Name</td> <!-- If we've output a fifth cell, break to a new row --> if (++counter % 5 == 4) { </tr><tr> } } </tr> </table> 

However, it would probably be better to output fixed-level block-level elements instead and place them to the left like this (excuse the inline styles ;-)):

 <div style="width: 300px;"> @foreach (var car in Model.Cars) { <div style="float: left; width: 55px;">@car.Name</div> } </div> 
+3
source

All Articles