I am learning mvc and try to populate checkbox list and get all selected values of checkbox list on submit button but i get null on button submit in the controller after post.The code for view and controller are as follows. The httpget part is working properly and shows all the checkbox as required. but after submitting problem occurs
View :
@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>
Controller:
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();
}
}