Why @Html.Checkboxfor returns "true,false"

Asked

Viewed 1,108 times

5

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

public bool? RegistoGesOleos { get; set; }

Who 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 the Controller (using Formcollection):

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

I receive as:

"true, false"

Edit: When inspecting items on my page, I found 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 it happens and how can I get around in the right way?

1 answer

8


This is because of the html construction 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 your html formed on the screen.

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

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

If there were no Hidden input it would be:

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

How to retrieve information:
The ModelBinder recovers these values perfectly for you. (If you are using a 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 filled with the values that came in the request. Who creates and fills this object is the Modelbinder.

  • Exactly, that’s what’s happening

  • check out how to treat.

  • that’s exactly what ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.