SBurris
SBurris

Reputation: 7448

ASP.NET MVC 3 Razor view returning multiple values for a Html.CheckBoxFor

I have a View that contains the following Line of code:

//(DaysOfWeek is a bool[])
@Html.CheckBoxFor(m => m.Data.DaysOfWeek[0])

It starts off as false. When the user "checks" the box and returns, it returns a value for both true and false;

Here is what is being passed back as part of the form data

Data.DaysOfWeek[0]:true
Data.DaysOfWeek[0]:false

Why is it doing that?

Upvotes: 5

Views: 1803

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

This is because standard HTML checkboxes return no value if unchecked. To make this annoying behaviour more intuitive, the CheckBoxFor method creates a checkbox and a hidden control with the same name, with a value of false, something like this:

<input type="checkbox" name="myControl" value="True" /> My control
<input type="hidden" name="myControl" value="False" />

What you will see when the form is posted is either:

False // checkbox unchecked
True,False // checkbox was checked

Therefore, to test if the box was checked you should use Contains('True'):

bool checkboxChecked = formCollection["myControl"].Contains("True");

Upvotes: 6

Related Questions