在循环/foreach MVC 视图中动态生成表 [英] Dynamically generate table in loop / foreach MVC view
问题描述
我现在正在编写一些非常糟糕的代码,在我什至保存它之前,我希望得到一些改进它的意见.我正在尝试构建一个每行三个单元格的 html 表.如果集合有 5 个项目,则应呈现为两行.
I am writing some very poor code right now and before I even save it I was hoping to get some input on improving it. I am trying to build an html table with three cells to every row. If the collection has 5 items then that should render as two rows.
到目前为止我所写的代码不是很健壮,需要不断维护,但我不确定是否有其他工具/方法可以完成任务.
The code I have written so far I can see is not very robust and will require constant maintenance but I am unsure of other tools / methods for accomplishing the task.
<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 进行比较:
You should considering using modulo instead of comparing the values of cellCount to 0, 3 or 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>
这篇关于在循环/foreach MVC 视图中动态生成表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!