A new row in the table every 4th cycle

How to create a new table row on every 4th cycle in the Razor view? This creates a new line for each number up to 4, and then completes the creation of new lines:

@{ int i = 0; } @foreach (var item in ViewBag.ProgramIdList) { if((i / 4) == 0) { @:<tr> } <td> <input type="checkbox" name="@item.ProgramId" id="@item.ProgramId" /> <label for="@item.ProgramTitle">@item.ProgramTitle</label> </td> if((i / 4) == 0) { @:</tr> } i++; } 
+4
source share
3 answers

Use the modulo operator. For:

 if((i % 4) == 0) { @:<tr> } 

and

 if((i % 4) == 3) { @:</tr> } 

If the number of elements is not divided into even rows, you must add the remaining cells and the line close tag after the loop:

 if ((i % 4) != 0) { while (i % 4) != 0) { @:<td></td> i++; } @:</tr> } 
+17
source

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 :-)

+6
source

The exact solution that works 100%.

  @foreach (var item in ViewBag.data) { var cells = totalCells; if ((i % cells) == 0) { @:<tr> } <td> @item.Value </td> if ((i % cells) == (cells - 1)) // aka: last row cell { @:</tr> } i++; } 
0
source

Source: https://habr.com/ru/post/1438093/


All Articles