How do I create a new table row on every 4th loop in my Razor View? This is creating a new row for each number before 4, and then quits creating new rows:
  @{
            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++;
         }
                Use the modulo operator. For :
if((i % 4) == 0)
{
  @:<tr>
}
and
if((i % 4) == 3)
{
  @:</tr>
}
If the number of items doesn't divide into even rows, you would add the remaining cells and a closing row tag after the loop:
if ((i % 4) != 0) {
  while (i % 4) != 0) {
    @:<td></td>
    i++;
  }
  @:</tr>
}
                        For those that hates the syntax higlight warning that appears with the code of the answer above, there is the 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 right position (<td> inside <tr>, <tr> inside <table>), then your Visual Studio syntax highlighter will leave you in peace :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With