Вот как вы это делаете. Это лучше, чем учебник. https://dotnetfiddle.net/RAHnmz
Контроллер / Просмотр модели
namespace Testy20161006.Controllers
{
public class CheckBoxItem
{
public string Text { get; set; }
public string Value { get; set; }
public bool Selected { get; set; }
}
public class CheckBoxList
{
public IList<CheckBoxItem> CheckBoxItems { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult Tut158(CheckBoxList checkBoxList)
{
return View(checkBoxList);
}
public ActionResult Tut158()
{
//creating viewmodel with Even Numbers checked
CheckBoxItem cbi1 = new CheckBoxItem { Text = "Text1", Value = "Value1", Selected = false };
CheckBoxItem cbi2 = new CheckBoxItem { Text = "Text2", Value = "Value2", Selected = true };
CheckBoxItem cbi3 = new CheckBoxItem { Text = "Text3", Value = "Value3", Selected = false };
CheckBoxItem cbi4 = new CheckBoxItem { Text = "Text4", Value = "Value4", Selected = true };
CheckBoxList cbl = new CheckBoxList();
cbl.CheckBoxItems = new List<CheckBoxItem>();
cbl.CheckBoxItems.Add(cbi1);
cbl.CheckBoxItems.Add(cbi2);
cbl.CheckBoxItems.Add(cbi3);
cbl.CheckBoxItems.Add(cbi4);
return View(cbl);
}
View
@model Testy20161006.Controllers.CheckBoxList
@{
Layout = null;
}
@using Testy20161006.Controllers
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut158</title>
</head>
<body>
<div>
@using (Html.BeginForm())
{
for (var i = 0; i < Model.CheckBoxItems.Count; i++)
{
@Html.Label(Model.CheckBoxItems[i].Text)
@Html.CheckBoxFor(
m => Model.CheckBoxItems[i].Selected)
@Html.HiddenFor(m => Model.CheckBoxItems[i].Text)
@Html.HiddenFor(m => Model.CheckBoxItems[i].Value)
}
<input type="submit" value="Post" />
}
</div>
</body>
</html>