【发布时间】:2019-12-28 21:50:55
【问题描述】:
如何在使用 foreach 循环时为一组复选框创建唯一的名称引用?
@foreach (var item in Model.myClass.Where(i => i.ID1 == 0))
{
<input type="text" asp-for="@item.Stuff" />
<input type="text" asp-for="@item.Stuff" />
<input type="text" asp-for="@item.Stuff" />
}
HTML(输出)
<input type="checkbox" checked="checked" id="item_Stuff" name="item_Stuff">
<input type="checkbox" checked="checked" id="item_Stuff" name="item_Stuff">
<input type="checkbox" checked="checked" id="item_Stuff" name="item_Stuff">
我已经看到 Razor Pages 推荐 here 但是这建议使用 for 循环或显式索引,这在我的情况下不起作用,因为我的语句中需要 where 子句。
示例
@for (var i = 0; i < 5; i++)
{
<tr>
<td>
<input type="text" asp-for="Contacts[i].FirstName" />
</td>
<td>
<input type="text" asp-for="Contacts[i].LastName" />
</td>
<td>
<input type="text" asp-for="Contacts[i].Email" />
</td>
</tr>
}
【问题讨论】:
-
您可以尝试使用 htmlhelpers 而不是标签助手,即使使用 foreach 您也可以使用整数计数器毫无问题地生成它们。
-
@{var i=0;} @foreach(var item in collection){++i;}看看我是如何使用这种 html 方式而不是使用标签助手
-
@Alok 谢谢。实际上,我已经可以使用标准 html 实现我需要的东西了在这种情况下,您是否建议不要使用标签助手?
-
即使你可以做一些扩展,花这么多时间在 html 中已经可用的简单东西上是不值得的,另外,如果你使用直接 html,你知道事情不会变得复杂,它也会节省你的性能asp标签需要转换成html页面输出
-
@Alok 我认为你是对的。感谢您的洞察力。
标签: c# asp.net-core foreach .net-core razor-pages