【发布时间】:2015-11-23 20:01:26
【问题描述】:
我有一个带有表格的视图,其中显示了我的模型项。我已经提取了我观点的相关部分:
@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 字段的布尔值正确显示在视图中。
根据 Andrew Orlov 的回答,我已经修改了视图和控制器,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; }
}
}
我的问题是,当单击“SaveAndSend”按钮时,从每个复选框中获取选中/未选中值并更新每个模型项的会话 IncludeProvision 字段的最佳方法是什么?
【问题讨论】:
-
您应该只有一个
HttpPost方法而不是JavaScript 重定向,然后提交您的模型,然后您可以将您的数据放入会话中并进行重定向。 -
尽量避免在视图中检查模型是否为空。在您的情况下,这是控制器工作。
-
@AndrewOrlov 嗯,我只是在遵循 ReSharper 建议的代码重构,假设它没有完全优化以遵循 MVC 最佳实践。
标签: javascript c# asp.net asp.net-mvc