[英]Problems with combined view and IEnumerable model in asp.Net MVC
[英]Asp.net mvc view with Ienumerable model returns null on submit
我正在学习mvc并尝试填充复选框列表并在提交按钮上获取复选框列表的所有选定值,但发布后在控制器中的按钮提交上得到空值.view和controller的代码如下。 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(); } }
您需要使用索引器而不是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
您可以使用foreach循环,但是需要将其放置在beginform部分之外,否则每次循环通过时,都会用新的集合替换最后一组数据。
还请阅读此内容(使用CheckBoxFor的正确方法):)- 正确使用.net MVC Html.CheckBoxFor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.