Reputation: 3127
In my MVC
view I have a form
with method GET
. In that form I have several fields which works fine. After adding a checkbox
I found strange behavior. If that checkbox
is unchecked I have myCheckbox=false
in GET
parameter, but when I check the checkbox
I have myCheckbox=true&myCheckbox=false
.
My view:
...
@using (Html.BeginForm("MyAction", "MyController", FormMethod.Get)) {
<fieldset>
SomeInput: @Html.TextBox("someInput") <br />
...
MyCheckbox: @Html.CheckBox("myCheckbox") <br />
</fieldset>
}
...
With value data
in SomeInput
and unchecked checkbox
I'm getting url:
...?someInput=data&myCheckbox=false
and with checked checkbox
I'm getting:
...?someInput=data&myCheckbox=true&myCheckbox=false
Upvotes: 0
Views: 865
Reputation: 7448
That's normal behaviour.
Standard html forms do not send a checkbox unless it is checked. This would lead to a missing parameter in your querystring if the box is not checked.
The html helper generates an input type=hidden
for each input type=checkbox
that you ask for (and you would have noted this if you took a little time to check the generated html). This is done to ensure that the field is passed down whether it is checked or not. So in the "not checked" scenario the actual checkbox is ignored, and you only have the value from the hidden field:
myField=false
If the checkbox is checked both are passed down, with the same name:
myField=true&myField=false
If I remember correctly if you declare in the receiving actionmethod a parameters bool myField
the default ModelBinder takes care of this particular scenario and will net you true
when the checkbox is checked and false
when it is not.
Upvotes: 1