How can I get the CheckBox to maintain checked state via postback in ASP.NET MVC?
I have an ASP.NET MVC project with a form. In the Action method that handles the POST verb, I have a custom implementation IModelBinder
that binds the form data to my model instance. If there are errors, I use bindingContext.ModelState.SetAttemptedValue()
and bindingContext.ModelState.AddModelError()
to store the posted value and the error message in ModelState
.
This works great and I can see the expected behavior on my input elements being rendered with Html.TextBox()
(which calls before Html.InputHelper()
). When I use Html.CheckBox()
(which also calls before Html.InputHelper()
), the state of my CheckBox is NOT outputted to the tag <input />
.
It seems to me that the method Html.InputHelper()
does not use the AttemptedValue method from ModelState for input fields of type CheckBox.
Here is the code from ASP.NET MVC methodHtml.InputHelper()
.
Why is it that CheckBox tryedValue is not output to the input tag. Is there something I'm missing here, or do I need to manually handle this case by checking the ModelState and setting the tag attribute myself?
Update 11/09
Here is the call HtmlHelpers
I am using to display the CheckBox:
<%= Html.CheckBox("IsDerived") %>
And here is the call I use to register the Attempt value:
string isDerivedRequestValue = !string.IsNullOrEmpty(bindingContext.HttpContext.Request["IsDerived"]) ? bindingContext.HttpContext.Request.Form.GetValues("IsDerived") [0] : null;
bindingContext.ModelState.SetAttemptedValue("IsDerived", isDerivedRequestValue);
I'm not sure if this is the best way to solve the problem or not, but since the method Html.InputHelper()
does not validate the TryemptedValue controls for the CheckBox, I added the following to my controller which inserts the correct value from ModelState
to ViewData
and seems to do the trick quite well.
ViewData["IsDerived"] = ViewData.ModelState.ContainsKey("IsDerived")
? bool.Parse(ViewData.ModelState["IsDerived"].AttemptedValue)
: false;
Make sure you don't explicitly set the parameter value isChecked
when you call Html.CheckBox()
, as this will override any value stored in ViewData
.