我是剃刀引擎语法的新手,在视图中添加逻辑时遇到了格式化问题。这就是我想要实现的目标。我收集了一些来自模型的物品。我需要迭代该集合,并在一行中对齐6个项目。
最终输出应该是这样的:
<table>
<tr>
<td>checkbox comes here</td>
<td>checkbox comes here</td>
<td>checkbox comes here</td>
</tr>
<tr>
<td>checkbox comes here</td>
<td>checkbox comes here</td>
<td>checkbox comes here</td>
</tr>
................. and so on
</table>
这是我在视图中写的代码
<table>
@for (int i = 0; i <= Model.checkItems.Count; i++)
{
if (i % 6 == 0)
{ <tr> }
<td>
<input type="checkbox"
id="chk_@(Model.checkItems[i].DisplayText)"
name="chk"
nameVal = "@Model.checkItems[i].DisplayText"
value="@Model.checkItems[i].Value"/>
<label for="chkGroup_@(Model.checkItems[i].DisplayText)">@Model.checkItems[i].DisplayText
</td>
if(i % 6 == 0)
{ </tr> }
}
</table>
当页面最终呈现时,执行第一个if条件,但不执行第二个if条件。有人能帮忙弄清楚如何做到这一点吗?
试试这个
<table>
@{ int count = 0; }
<tr>
@foreach (var item in Model.checkItems)
{
<td>
<input type="checkbox"
id="chk_@(item.DisplayText)"
name="chk"
nameVal = "@item.DisplayText"
value="@item.Value"/>
<label for="chkGroup_@(item.DisplayText)">@item.DisplayText</label>
</td>
if (++count % 6 == 0)
{
@:</tr><tr>
}
}
</tr>
</table>
您的标签上缺少一个结束标记
<label for="chkGroup_@(Model.checkItems[i].DisplayText)">@Model.checkItems[i].DisplayText
应该是
<label for="chkGroup_@(Model.checkItems[i].DisplayText)">@Model.checkItems[i].DisplayText</label>
这会起作用吗:
<table>
@for (int i = 0; i <= Model.checkItems.Count; i++)
{
if (i % 6 == 0)
{
<tr>
<td>
<input type="checkbox"
id="chk_@(Model.checkItems[i].DisplayText)"
name="chk"
nameVal = "@Model.checkItems[i].DisplayText"
value="@Model.checkItems[i].Value"/>
<label for="chkGroup_@(Model.checkItems[i].DisplayText)">@Model.checkItems[i].DisplayText
</td>
</tr>
}
}
</table>
下面是另一个对行和列使用2个嵌套循环的解决方案。我不知道它是否一定更好(从表面上看肯定更复杂),但它至少可以让你轻松地看到行和单元格的嵌套性质:
<table>
@{
const int cols = 3;
int rows = (Model.checkItems.Count + cols - 1) / cols;
}
@for (int rowIndex = 0; rowIndex < rows; rowIndex++)
{
<tr>
@for (int colIndex = rowIndex * cols; colIndex < Math.Min(Model.checkItems.Count, cols * (rowIndex + 1)); colIndex++)
{
<td>
<input type="checkbox"
id="chk_@(Model.checkItems[colIndex].DisplayText)"
name="chk"
nameVal="@Model.checkItems[colIndex].DisplayText"
value="@Model.checkItems[colIndex].Value"/>
<label for="chkGroup_@(Model.checkItems[colIndex].DisplayText)">@Model.checkItems[colIndex].DisplayText</label>
</td>
}
</tr>
}
</table>