Foreach in BeginForm 和 RadioButtonFor() 元素中的显示元素
本文关键字:元素 显示 in BeginForm RadioButtonFor Foreach | 更新日期: 2023-09-27 18:33:41
我正在使用C#.NET MVC3(Razor)来创建一个简单的表单。但是在这种形式中,我需要以单选按钮的形式打印列表的内容。但我不确定这是如何工作的:
@using(Html.BeginForm("Method", "Controller", FormMethod.Post))
{
foreach (Items item in Model.Items)
{
<div>
@Html.RadioButtonFor(item->itemId)
@Html.LabelFor(item->description)
</div>
}
}
但这行不通。
我可能可以使用普通的 html 标签来创建单选按钮。但是数据不会自动保存在正确的位置吗?
我怎样才能做到这一点?
我建议您使用编辑器模板而不是编写这些循环:
@model MyViewModel
@using(Html.BeginForm("Method", "Controller", FormMethod.Post))
{
@Html.EditorFor(x => x.Items)
}
现在定义一个相应的编辑器模板,该模板将自动为模型的每个元素渲染(~/Views/Shared/EditorTemplates/ItemViewModel.cshtml
):
@model ItemViewModel
<div>
@Html.RadioButtonFor(x => x.itemId, "1")
@Html.LabelFor(x => x.description)
</div>
请注意,除了选取相应视图模型属性的 lambda 表达式之外,您还必须将第二个参数传递给Html.RadioButtonFor
帮助程序。此参数表示如果用户在提交表单时选中此单选按钮,则将发送到服务器并绑定到相应属性的值。
另请注意,这是按照惯例工作的。如果我们假定主视图模型中的 Items 属性类型为 IEnumerable<ItemViewModel>
,则必须定义并将为此集合的每个元素呈现的相应编辑器模板~/Views/Shared/EditorTemplates/ItemViewModel.cshtml
或~/Views/CurrentController/EditorTemplates/ItemViewModel.cshtml
(如果您不希望在多个控制器之间共享此模板)。
当你在foreach循环中时。 以下将起作用。
foreach (Items item in Model.Items)
{
<div>
@Html.RadioButtonFor(item.itemId)
@Html.LabelFor(item.description)
</div>
}
如果要保存它们,则需要实现基于零索引的解决方案,如下所示
@{int i = 0}
foreach (Items item in Model.Items)
{
<div>
@Html.RadioButtonFor(model =>model[i].itemId)
@Html.LabelFor(model =>model[i].description)
</div>
i++;
}
语法有点不同:
@Html.RadioButtonFor(model => item.ItemId)
@Html.LabelFor(model => item.Description)
其他一切看起来都很好。
[编辑] 哇,我一定累了。是的,以下内容看起来不错,但仅用于显示。检查达林的编辑器模板答案。
[编辑2] 从问题中看不是很明显,但从您的评论中似乎 foreach 中的item
是另一个枚举。然后嵌套 foreach 循环,以显示属性:
@foreach(var itemList in Model.Items)
{
foreach(var item in itemList)
{
<div>
@Html.RadioButtonFor(model => item.ItemId)
@Html.LabelFor(model => item.Description)
<div>
}
}
是这样吗?我仍然不确定我是否正确理解它。:)