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 in UK. You can always start from their start from €3.00/month and this plan has supported ASP.NET MVC 6, within less than 5 minutes. They provide cheap, best and instant activation on your web hosting account with UNLIMITED Bandwidth, Diskspace and Domain.
They hired an army of the very best technicians, managers and web hosting gurus. That means clear, professional support, fast. Their team are standing by to respond to your queries around the clock, big or small, and they’ll be there for you – 24×7, 365 days a year. You can contact them via all standard communication channels – by e-mail, through the ticketing system, or via an online form – should you have any pre-sales questions.
Their top priority to deliver the ultimate customer experience, and they strongly believe that you’ll love their service – so much so that if for any reason you’re unhappy in your first 30 days as a customer, you’re more than welcome to request your money back. They have just one request – that you let them know why you’re unhappy so they can address the problem for their other customers and make their service even better.