Webcognoscere Webcognoscere - 4 months ago 34
ASP.NET (C#) Question

Why does the CheckBoxFor render an additional input tag, and how can I get the value using the FormCollection?

In my ASP.NET MVC app, I am rendering a checkbox using the following code:

<%= Html.CheckBoxFor(i=>i.ReceiveRSVPNotifications) %>

Now, I see that this renders both the checkbox input tag and a hidden input tag. The problem that I am having is when I try retrieve the value from the checkbox using the FormCollection:


I get the value "true,false". When looking at the rendered HTML, I can see the following:

<input id="ReceiveRSVPNotifications" name="ReceiveRSVPNotifications" value="true" type="checkbox">
<input name="ReceiveRSVPNotifications" value="false" type="hidden">

So the FormValues collection seems to join these two values since they have the same name.

Any Ideas?


Have a look here:


This isn't a bug, and is in fact the same approach that both Ruby on Rails and MonoRail use.

When you submit a form with a checkbox, the value is only posted if the checkbox is checked. So, if you leave the checkbox unchecked then nothing will be sent to the server when in many situations you would want false to be sent instead. As the hidden input has the same name as the checkbox, then if the checkbox is unchecked you'll still get a 'false' sent to the server.

When the checkbox is checked, the ModelBinder will automatically take care of extracting the 'true' from the 'true,false'