Why @ Html.CheckBoxFor returns "true, false"

5

In the construction of my View, I have a field of type:

public bool? RegistoGesOleos { get; set; }

What I represent using Razor as:

@Html.CheckBoxFor(model => model.RegistoGesOleos.Value)

Now when I do submit of my Form, and I try to get the value of the field in Controller (using FormCollection):

var teste = form["ConcluidoGesOleos.Value"];

I get as:

  

"true, false"

Edit: When I inspected elements on my page, I noticed that two input's are created:

<input data-val="true" data-val-required="The Value field is required." id="ConcluidoGesOleos" name="ConcluidoGesOleos.Value" type="checkbox" value="true">
<input name="ConcluidoGesOleos.Value" type="hidden" value="false">

Why does this happen and how can I get around it in the right way?

    
asked by anonymous 27.10.2014 / 16:09

1 answer

7

This is because of the construction of the html on the page. CheckBoxFor builds something similar to this:

<input type="checkbox" name="RegistoGesOleos.Value" value="true" />
<input type="hidden" name="RegistoGesOleos.Value" value="false" />

Check out your on-screen html.

Razor was created in this way to prevent the absence of the field in page serialization. When the checkbox is not selected the value of it is not included in the serialization of the page. So you have the following situations:

1st - Checkbox case is selected serialization will be: RegistoGesOleos.Value=true,false . 2 - If checkbox is not selected the serialization will be: RegistoGesOleos.Value=false .

If there was no input hidden it would be:

1st - If checkbox was selected the serialization would be: RegistoGesOleos.Value=true . 2 - If checkbox was not selected the serialization would be: (Nothing).

How to retrieve information:
ModelBinder recovers these values to perfection for you. (If you are using any ModelBinder) or you can, if you are not using ModelBinder, do something like:

var boolvalue = form["ConcluidoGesOleos.Value"].Contains("true");

OBS:
If you do not know, you use ModelBinder when you write something in the parameter of your action method. ex:

public ActionResult MinhaAction(ModelRegistros model) { ... }

The object model is populated with the values that came in the request. Whoever creates and populates this object is ModelBinder.

    
27.10.2014 / 16:18