【问题标题】:Dynamically generate table in loop / foreach MVC view在循环/foreach MVC 视图中动态生成表
【发布时间】:2013-12-10 22:13:08
【问题描述】:

我现在正在编写一些非常糟糕的代码,在我保存它之前,我希望得到一些改进它的意见。我正在尝试构建一个每行包含三个单元格的 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>

【问题讨论】:

  • 对于初学者来说,没有必要将&lt;tr&gt; 包裹在@Html.Raw()
  • 当我没有将它包裹在原始文件中时,我会收到错误,如果没有找到右大括号。如这里所述:forums.asp.net/t/1654550.aspx

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


【解决方案1】:

您应该考虑使用模数而不是将 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>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-01-20
  • 2019-04-15
  • 1970-01-01
  • 2012-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-09
相关资源
最近更新 更多