Search code examples
asp.netasp.net-mvcasp.net-mvc-4checkboxcheckboxfor

ASP.net MVC Checkbox Issue


I am working on an ASP.net MVC project and I am using the CheckBoxFor helper method to provide the value for a boolean in my model like so:

@Html.CheckBoxFor(m => m.ShouldSaveSearch, new { id="ShouldSaveSearch"})

If the checkbox gets checked by the user, it works completely fine and when the model is received by the controller. The ShouldSaveSearch property will be set to true.

[HttpGet]
public ActionResult Search(int studentSearchId = -1)
{
    return View(new StudentSearchModel(studentSearchId));
}

[HttpPost]
public ActionResult Search(StudentSearchModel m)
{
    ViewBag.SearchResults = Hub.Web.Models.Student.StudentSearchModel.Search(m);
    Hub.Web.Models.Student.StudentSearchModel.Save(m);
    m.ShouldSaveSearch = false;
    m.ShouldShareSearch = false;
    m.SavedSearchName = "";
    m.SavedSearchDescription = "";

    return View(m);
}

I then set the ShouldSaveSearch property to false and then return the same view with the same model that was originally submitted.

However, when the view renders, the checkbox for this property remains checked. Is there something that I am missing that is preventing the checkbox from unchecking itself?


Solution

  • It sounds like the ModelState problem discussed in this question and also here

    In a few words the HtmlHelper displays ModelState value not Model. See question for more details.

    Possible options:

    • Implement the post-redirect-get pattern as suggested by Forty-Two
    • Reset the checkbox value using the ModelState collection, something like ModelState["ShouldSaveSearch"].Value = false