For those who hate the higlight syntax warning that appears with the code for the answer above, there is a solution (the mechanism is about the same):
<table> @for (int i = 0; i < ViewBag.MyItems.Count; i++) { var cells = 4; var item = ViewBag.MyItems[i]; if ((i % cells) == 0) { @:<tr> } <td> @item.MyTextOrWhatever </td> if (i == (ViewBag.MyItems.Count - 1)) { while ((i % cells) != 0) { @:<td></td> i++; } } if ((i % cells) == (cells - 1)) // aka: last row cell { @:</tr> } } </table>
Each tag is in the correct position ( <td> inside <tr> , <tr> inside <table> ), then Visual Studio syntax syntax will leave you alone :-)
source share