Javascript ASP.Net MVC复选框值从视图到自定义控制器方法
我有一个视图,其中包含一个显示模型项的表。我提取了我的观点的相关部分:Javascript ASP.Net MVC复选框值从视图到自定义控制器方法,javascript,c#,asp.net,asp.net-mvc,Javascript,C#,Asp.net,Asp.net Mvc,我有一个视图,其中包含一个显示模型项的表。我提取了我的观点的相关部分: @model System.Collections.Generic.IEnumerable<Provision> @using (Html.BeginForm("SaveAndSend", "Provision", FormMethod.Post)) { if (Model != null && Model.Any()) { <table class="ta
@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>
}
...
}
但是,此时传入的模型对象为null
包括完整性规定模型对象:
namespace
{
public partial class Provision
{
...
// other fields
...
public bool IncludeProvision { get; set; }
}
}
我的问题是,单击“保存并发送”按钮时,从每个复选框中获取选中/未选中的值并更新每个模型项的会话
IncludeProvision
字段的最佳方法是什么?正如@mattytomo在评论中所说的,您应该将您的模型发布到控制器。这可以通过将复选框放入表单中来完成。单击“保存并退出”按钮后,此表单中输入的所有数据都将被序列化并发送到控制器,在那里您可以使用会话变量执行操作,等等。之后,你可以重定向到任何你喜欢的地方
型号
public class YourModel
{
...
public bool IncludeProvision { get; set; }
...
}
查看
@model YourModel
...
@using (Html.BeginForm("SaveAndSend", "Test", FormMethod.Post))
{
...
@Html.CheckBoxFor(model => model.IncludeProvision)
...
<button type="submit">Save and send</button>
}
...
不能使用
foreach
循环为集合中的属性生成表单控件。它会创建与模型无关的重复的name
属性(在您的示例中为name=“item.IncludeProvision”
),并创建无效的id
属性。使用for
循环(您的模型需要IList
在主视图中(模型可以是IEnumerable
)
@EditorFor(m=>m)
你应该有一个HttpPost
方法,而不是JavaScript重定向,然后提交你的模型,然后你可以将你的数据放在会话中并进行重定向。尽量避免在视图中检查模型是否为空。这是你的控制器工作。@AndrewOrlov-hmm我刚刚在这一个问题上遵循了ReSharper建议的代码重构,假设它没有完全优化以遵循MVC最佳实践。嗯,视图中我的模型类型是列表
,而不是规定
。使用HttpPost
将表包装成带有以下签名的表单到我的控制器方法,将导致空规定
对象。公共操作结果保存和发送(列出规定)
您是如何生成表的?分析您的模型。使用foreach列表创建每个模型,当您提交帖子时,您将检索模型。我们应该查看您的视图和模型以获得更准确的答案。@User.Anonymous这正是我生成表的方式。@AndrewOrlov用视图、控制器和方法的片段更新了我的问题型号代码。谢谢你的帮助
@model YourModel
...
@using (Html.BeginForm("SaveAndSend", "Test", FormMethod.Post))
{
...
@Html.CheckBoxFor(model => model.IncludeProvision)
...
<button type="submit">Save and send</button>
}
...
public class TestController : Controller
{
...
[HttpPost]
public ActionResult SaveAndSend(YourModel model)
{
if (ModelState.IsValid)
{
// Some magic with your data
return RedirectToAction(...);
}
return View(model); // As an example
}
...
}
for(int i = 0; i < Model.Count; i++)
{
<tr>
<td>....</td>
<td>@Html.CheckBoxFor(m => m[i].IncludeProvision)<td>
</tr>
}
@model Provision
<tr>
<td>....</td>
<td>@Html.CheckBoxFor(m => m.IncludeProvision)<td>
</tr>
<table>
@Html.EditorFor(m => m)
</table>