5

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?

1
  • Although @RoryMcCrossan explained the why, and a answer, I have never seen this problem, doing what you are doing. Could you post your view model, I would think bool DayOfWeek0 = Data.DaysOfWeek[0] should be either true or false if you're not using a view model, you could just do @Html.CheckBox("VariableName") and in your controller method arguments bool VariableName Commented Aug 4, 2012 at 20:37

1 Answer 1

6

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");
Sign up to request clarification or add additional context in comments.

1 Comment

This pestilent feature is also resolved when using binding libraries, such as knockout.js...binding directly to a Boolean occurs flawlessly. I find it best to not use RazorFor syntax in most situations, but if you still do, the checked property can be overridden with a data-bind attribute and works great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.