How can I get Html.CheckBox () as boolean during POST in a custom IModelBinder?
I am using Html.CheckBox()
. Final HTML:
<input id="IsMultiGraph" name="IsMultiGraph" value="true" type="checkbox">
<input name="IsMultiGraph" value="false" type="hidden">
On the server, I have an action that takes information about a form post and uses a custom IModelBinder to bind the form results to one of my models. Here is the piece of code I am running in the IModelBinder:
bool isMultiGraph;
if (!bool.TryParse(bindingContext.HttpContext.Request["IsMultiGraph"], out isMultiGraph))
bindingContext.ModelState.AddModelError("IsMultiGraph", "Invalid boolean for \"IsMultiGraph\""); //this should not ever happen unless someone is programatically posting
result.IsMultiGraph = isMultiGraph;
The problem is that, since it Html.CheckBox()
creates a checkbox as well as a hidden input field, if I change the state of the textbox, the back copy value is doubled (ie "true, false").
I understand why this is done and I am looking for a better way to parse the current CheckBox value during postback (checked = true, unchecked = false). Is there another helper method in MVC for this, or should I just write my own?
source to share