在循环/ foreach MVC视图中动态生成表

时间:2013-12-10 22:13:09

标签: asp.net-mvc html5 asp.net-mvc-3 razor

我现在正在编写一些非常糟糕的代码,在我保存它之前,我希望得到一些改进它的输入。我正在尝试构建一个每行有三个单元格的html表。如果集合有5个项目,则应该呈现为两行。

到目前为止我写的代码我看得不是很强大,需要不断维护,但我不确定完成任务的其他工具/方法。

<table>
    @foreach (VideosModel item in Model)
    {
        if (cellCount == 0 || cellCount == 3)
        { 
            @Html.Raw("<tr>") 
        }
           <td style="padding:0px 20px;">
                @item.VideoTitle <br />
                <a href="@item.VideoUrl" target="_blank">
                    <img src="../../.../Video.jpg" /> <br />
                </a>
                @item.VideoDescription
                <br />
            </td>

        cellCount++;

        if (cellCount == 3 || cellCount == 6)
        { 
            @Html.Raw("</tr>") 
        }

        if (cellCount > 3) { cellCount = 0; }
    }
</table>

1 个答案:

答案 0 :(得分:8)

您应该考虑使用modulo而不是将cellCount的值与0,3或6进行比较:

<table>
    @foreach (VideosModel item in Model)
    {
        if (cellCount % 3 == 0)
        { 
            @:<tr>
        }
           <td style="padding:0px 20px;">
                @item.VideoTitle <br />
                <a href="@item.VideoUrl" target="_blank">
                    <img src="../../.../Video.jpg" />
                </a><br />
                @item.VideoDescription
                <br />
            </td>

        cellCount++;

        if (cellCount % 3 == 0)
        { 
            @:</tr>
        }
    }
</table>
相关问题