views:

138

answers:

1

Hi, In my ASP.NET MVC app I am rendering out 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 out 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?

+6  A: 

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'

Robert Harvey
That's a good explanation but in some cases you might want to get 'nothing' in the query string when the ckecbox is not checked - so the default behaviour. Is this possible using the Html helper or do I have to simply use the `<input>` tag.
brainnovative