提交按钮只发送第一个复选框值
submit button only sends the first checkbox value
我有一个简单的项目,我想通过 asp.net mvc 中的表单和多个复选框发送信息。
这是观点:
这是控制器方法:
[HttpPost]
public ActionResult Index(Customer customer)
{
if (customer != null)
{
return Content(customer.Name.ToString());
}
return Content("empty");
}
我知道我在控制器方法中得到了一个变量,但关键是如果我把一个 IEnumerable
类型像列表、数组甚至 IEnumerable
本身,我将收到 null 值, 如果我放一个变量,视图页面只发送第一个复选框的值。
在这里你可以看到我选择了 B 选项,但视图仍然 returns A 选项。
绑定到列表的模型不能很好地与 foreach
一起使用;您需要改用 for
。
这意味着您需要将模型更改为可索引列表。
@model IReadOnlyList<WebApplication2.Models.Customer>
...
@for (int index = 0; index < Model.Count; index++)
{
<tr>
<td>@Html.DisplayFor(m => m[index].Name)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { Model[index].ID })
@Html.ActionLink("Details", "Details", new { Model[index].ID })
@Html.ActionLink("Delete", "Delete", new { Model[index].ID })
@Html.CheckBoxFor(m => m[index].IsSelected)
@Html.HiddenFor(m => m[index].ID)
@Html.HiddenFor(m => m.[index].Name)
</td>
</tr>
}
我有一个简单的项目,我想通过 asp.net mvc 中的表单和多个复选框发送信息。
这是观点:
这是控制器方法:
[HttpPost]
public ActionResult Index(Customer customer)
{
if (customer != null)
{
return Content(customer.Name.ToString());
}
return Content("empty");
}
我知道我在控制器方法中得到了一个变量,但关键是如果我把一个 IEnumerable
类型像列表、数组甚至 IEnumerable
本身,我将收到 null 值, 如果我放一个变量,视图页面只发送第一个复选框的值。
在这里你可以看到我选择了 B 选项,但视图仍然 returns A 选项。
绑定到列表的模型不能很好地与 foreach
一起使用;您需要改用 for
。
这意味着您需要将模型更改为可索引列表。
@model IReadOnlyList<WebApplication2.Models.Customer>
...
@for (int index = 0; index < Model.Count; index++)
{
<tr>
<td>@Html.DisplayFor(m => m[index].Name)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { Model[index].ID })
@Html.ActionLink("Details", "Details", new { Model[index].ID })
@Html.ActionLink("Delete", "Delete", new { Model[index].ID })
@Html.CheckBoxFor(m => m[index].IsSelected)
@Html.HiddenFor(m => m[index].ID)
@Html.HiddenFor(m => m.[index].Name)
</td>
</tr>
}