开发者

Foreach loop table, max 2 cells then a new row?

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?


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>


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.


You want to look at using the modulus operator (%).

Something like

if i%2 = 0 { new line }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜