我正在学习 mvc 并尝试填充复选框列表并在提交按钮上获取复选框列表的所有选定值,但我在发布后在控制器中提交按钮时为空。视图和控制器的代码如下。httpget 部分工作正常,并根据需要显示所有复选框。但是提交后出现问题查看:@model IEnumerable<MVCExtra.Models.paymentmethod>@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>Index</title></head><body>@using(Html.BeginForm("Index", "Input", FormMethod.Post, new { @class = "form-horizontal", role = "form" })){ foreach (var item in Model) { @Html.HiddenFor(x => item.Id); @Html.HiddenFor(x => item.Name); @Html.CheckBoxFor(x=>item.isselected); @Html.DisplayFor(x => item.Name); } <input type="submit" value="submit"/>}</body></html>控制器: public ActionResult Index() { List<paymentmethod> listpay = new List<paymentmethod>() { new paymentmethod() { Id="CS",isselected = true,Name = "Cash"}, new paymentmethod() { Id="CH",isselected = false,Name = "Cheque"}, new paymentmethod() { Id="CR",isselected = false,Name = "Credit"}, new paymentmethod() { Id="BN",isselected = false,Name = "Bank"} }; return View(listpay); } [HttpPost] public string Index(IEnumerable<paymentmethod> model) { if (model.Count(x => x.isselected) == 0) { return "no any option is selected"; } else { StringBuilder sb = new StringBuilder(); sb.Append("You selected:"); foreach (paymentmethod pay in model) { if (pay.isselected == true) { sb.Append(":" + pay.Name); } } return sb.ToString(); } }
2 回答
慕娘9325324
TA贡献1783条经验 获得超4个赞
您需要使用索引器而不是 foreach 循环来使模型正确回发
for(int i=0; i < Model.Count(); i++)
{
@Html.HiddenFor(x => Model[i].Id);
@Html.HiddenFor(x => Model[i].Name);
@Html.CheckBoxFor(x=>Model[i].isselected);
@Html.DisplayFor(x => Model[i].Name);
}
编辑:忘了提及,您需要将模型转换为列表而不是 IEnumerable
- 2 回答
- 0 关注
- 189 浏览
添加回答
举报
0/150
提交
取消