leora
leora

Reputation: 196539

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

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

I want to show 5 cars per row, 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>

The issues are I feel like the code above is a little hacky and also what if I have 7 cars, should I put 3 blank <td>s in the last row or cut it off (again even more hacky code)?

I wanted to see if there was a cleaner way in an asp.net-mvc to display a collection in a table with a specific number of entries in the table on a row.

Upvotes: 4

Views: 2473

Answers (2)

Major Byte
Major Byte

Reputation: 4101

If you want to stick to tables, this looks the least hacky to 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 out the last row with <td> elements, you can put this in front of the <tr>:

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

Upvotes: 4

Danny Tuppeny
Danny Tuppeny

Reputation: 42343

You could make this slightly cleaner with something along these lines:

<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 instead output block-level elements with a fixed width and float them 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>

Upvotes: 3

Related Questions