Webcognoscere Webcognoscere - 1 month ago 14
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:

FormValues["ReceiveRSVPNotifications"]


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?

Answer

Have a look here:

http://forums.asp.net/t/1314753.aspx

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'