Austin Agile DevOps

DevOps in the Cloud
posts - 70 , comments - 7 , trackbacks - 0

Retain and Set Posted Checkbox Value in the MVC 4 Controller

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

public bool 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 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");
        }

Print | posted on Monday, March 11, 2013 10:27 AM |

Feedback

Gravatar

# re: Retain and Set Posted Checkbox Value in the MVC 4 Controller

I had the same problem and couldn't find a solution anywhere. Your solution worked, but then I ran across a cleaner one at the link below. I think it is a bug, but @Html.EditorFor() resolves it nicely.

http://stackoverflow.com/questions/14730746/getting-checkbox-value-in-asp-net-mvc-4
7/25/2013 4:54 PM | Baer Kenney
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: