gpt4 book ai didi

javascript - 从 View 到自定义 Controller 方法的 ASP.Net MVC 复选框值

转载 作者:行者123 更新时间:2023-11-30 16:40:02 25 4
gpt4 key购买 nike

我有一个 View ,其中有一个显示我的模型项目的表格。我已经提取了我的观点的相关部分:

@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 字段的 bool 值正确显示在 View 中。

根据 Andrew Orlov 的回答,我修改了 View 和 Controller ,SaveAndSend() Controller 方法现在是:

[HttpPost]
public ActionResult SaveAndSend(List<Provision> provisions)
{
if (ModelState.IsValid)
{
// perform all the save and send functions
_provisionHelper.SaveAndSend(provisions);
}
return RedirectToAction("Index");
}

但是,此时传入的模型对象为null。

包括 Provision 模型对象以确保完整性:

namespace
{
public partial class Provision
{
...
// other fields
...
public bool IncludeProvision { get; set; }
}
}

我的问题是,当单击“SaveAndSend”按钮时,从每个复选框中获取选中/未选中值并更新每个模型项的 session IncludeProvision 字段的最佳方法是什么?

最佳答案

您不能使用 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 .在 /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>

关于javascript - 从 View 到自定义 Controller 方法的 ASP.Net MVC 复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32143473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com