我有一个带有显示我的模型项目的表格的视图。我提取了我的观点的相关部分:
@model System.Collections.Generic.IEnumerable<Provision>
@using (Html.BeginForm("SaveAndSend", "Provision", FormMethod.Post))
{
if (Model != null && Model.Any())
{
<table class="table table-striped table-hover table-bordered table-condensed">
<tr>
...
// other column headers
...
<th>
@Html.DisplayNameFor(model => model.IncludeProvision)
</th>
...
// other column headers
...
</tr>
@foreach (var item in Model)
{
<tr>
...
// other columns
...
<td>
@Html.CheckBoxFor(modelItem => item.IncludeProvision)
</td>
...
// other columns
...
</tr>
}
</table>
<button id="save" class="btn btn-success" type="submit">Save + Send</button>
}
...
}
这工作正常,并且复选框值根据布尔值在视图中正确显示IncludeProvision
给定模型项的字段。
根据安德鲁·奥尔洛夫的回答,我修改了视图和控制器以及SaveAndSend()
控制器方法现在是:
[HttpPost]
public ActionResult SaveAndSend(List<Provision> provisions)
{
if (ModelState.IsValid)
{
// perform all the save and send functions
_provisionHelper.SaveAndSend(provisions);
}
return RedirectToAction("Index");
}
然而,此时传入的模型对象为空。
为了完整性,包括 Provision 模型对象:
namespace
{
public partial class Provision
{
...
// other fields
...
public bool IncludeProvision { get; set; }
}
}
我的问题是,从每个复选框获取选中/未选中值并更新会话的最佳方法是什么IncludeProvision
单击“SaveAndSend”按钮时每个模型项的字段?
您不能使用foreach
循环为集合中的属性生成表单控件。它会创建重复的name
属性(在你的情况下name="item.IncludeProvision"
)与您的模型没有关系并且重复id
无效的 html 属性。使用任一for
循环(你的模型需要IList<Provision>
for(int i = 0; i < Model.Count; i++)
{
<tr>
<td>....</td>
<td>@Html.CheckBoxFor(m => m[i].IncludeProvision)<td>
</tr>
}
或创建一个EditorTemplate
对于类型Provision
. In /Views/Shared/EditorTemplates/Provision.cshtml
(注意模板的名称必须与类型的名称匹配)
@model Provision
<tr>
<td>....</td>
<td>@Html.CheckBoxFor(m => m.IncludeProvision)<td>
</tr>
并在主视图中(模型可以是IEnumerable<Provision>
)
<table>
@Html.EditorFor(m => m)
</table>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)