Originally posted on: http://geekswithblogs.net/BobHardister/archive/2013/03/11/retain-and-set-posted-checkbox-value-in-the-mvc-4.aspx
I believe this is a bug where only the checkbox value is not retained when passing the model from the view to a post method.
Model
publicbool CoreField { get; set; }
View
@model List<Model> @Html.CheckBoxFor(m => m[i].CoreField, new { @id = "cbCoreField" + i })@Html.HiddenFor(m => m[i].CoreField) @Html.Hidden("fIsCore", null, new { @id = "hIsCore" + i }) //has to use separate list instead of model due to MVC bug
Note the use of “fIsCore” as a separate list used to pass changes to the checkbox into the post method and the use of ModelState.SetModelValue to set the checkbox value for redisplay when the model is invalid (i.e. adding a row where the model validation rules for some other field has been violated.
Controller Post Method
[HttpPost]public ActionResult Index(List<Model> model, List<bool> fIsCore) {if (!(model == null)) {if (ModelState.IsValid) {int i = 0;foreach (var item in model) { item.CoreField = fIsCore[i]; i++;if (!(item.ID == 0)) { db.Entry(item).State = EntityState.Modified; }else { db.Model.Add(item); } } db.SaveChanges(); }else {//ModelState.Clear(); // not needed nowint i = 0;foreach (var item in model) {string key = string.Format("[{0}].CoreField", i); item.CoreField = fIsCore[i]; ModelState.SetModelValue(key, new ValueProviderResult(item.CoreField, "", CultureInfo.InvariantCulture)); i++; }return View(model); } }return RedirectToAction("Index"); }