我正在学习 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();
}
}
慕娘9325324
慕仙森
相关分类