tags:

views:

1145

answers:

1

I am using Html.CheckBox(). The resulting HTML is:

<input id="IsMultiGraph" name="IsMultiGraph" value="true" type="checkbox">
<input name="IsMultiGraph" value="false" type="hidden">

On the server I have an Action which is accepting the form post information and using a custom IModelBinder to bind the form results to one of my models. Here is a snippet of the 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 Html.CheckBox() is rendering a checkbox as well as a hidden input field if I change the state of the textbox the postback value is doubled (ie. "true,false").

I understand why this is done and I'm looking for the best way to parse the current value of the CheckBox during a postback (checked = true, unchecked = false). Is there another helper method in MVC for this or should I just write my own?

+1  A: 

One way is to use the GetValues method of the NameValueCollection class in order to get the first value of the array property like this:

bindingContext.HttpContext.Request.Form.GetValues("IsMultiGraph")[0]
Panos
That'll work, anyone know how ASP.NET MVC does it in their default binder. It seems like CheckBoxes are a special case. Maybe I was to tired, but I couldn't see where they were handling the checkbox and hidden input last night.
spoon16