New Table row every 4th loop

*爱你&永不变心* 提交于 2021-02-07 06:55:24

问题


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++;
         }

回答1:


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>
}



回答2:


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




回答3:


That the exact solution which 100% works.

            @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++;
            }


来源:https://stackoverflow.com/questions/12754516/new-table-row-every-4th-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!