我现在正在编写一些非常糟糕的代码,在我保存它之前我希望得到一些改进它的意见。我正在尝试构建一个 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>
最佳答案
您应该考虑使用模而不是将 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>
关于asp.net-mvc - 在循环/foreach MVC View 中动态生成表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20506432/