Reputation: 557
I have a question for my foreach loop on a table design in my mvc view.
I want my loop to output max 2 cells for each table row and if and it has data to loop out more than 2 cells it adds a new row and continues to loop out the data on the cells on that row etc..
Anyone have a solution for this?
Upvotes: 1
Views: 4559
Reputation: 2513
You want to look at using the modulus operator (%).
Something like
if i%2 = 0 { new line }
Upvotes: 2
Reputation: 887451
You shouldn't use tables for this.
Instead, put your content in <div>
s with float: left
or display: inline-block
, and make the parent element just wide enough to hold two children.
Upvotes: 3
Reputation: 532465
Iterate over the collection in increments of two. Check to make sure that the i+1th item is available before outputting it, outputting an empty cell instead if it isn't.
<table>
<thead>
<tr><th>Column 1</th><th>Column 2</th></tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Count(); i = i + 2)
{
<tr>
<td>@Model[i]</td> // or @Model.ElementAt(i)
<td>@(i+1 < Model.Count() ? Model[i+1] : "")</td> // similar
</tr>
}
</tbody>
</table>
Upvotes: 6