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?

+1


source to share


1 answer


One way is to use a GetValues

class method NameValueCollection

to get the first value of an array property like this:



bindingContext.HttpContext.Request.Form.GetValues("IsMultiGraph")[0]

      

+3


source







All Articles