I believe this is often a bug where only the checkbox value isn’t retained when passing the model from the view to a post method. Model public bool CoreField { get; set; } View
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | @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 now int 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"); } |
Choose the Best ASP.NET MVC 6 Web Hosting HostForLIFEASP.NET is recognized as one of the Best, Cheap Web Hosting Provider …