Friday, 9 November 2012

Handling unchecked checkboxes on form post


Wow - 2 years since i made a post on here!Oops. Guess i've been a little busy.

Anyway - i thought i just had to post this little nugget as it had me head scratching for a while.

You my be looking for a solution to any of the following:

Handling unchecked checkboxes on form post
Checkboxes missing from postback in asp.net web forms
Checkboxes missing from form on postback

or something of a similar ilk! Chances are its probably the same issue.

Except its not an issue - it seems its by design unfortunately.  No idea who made this decision but when a checkbox is not checked it is not posted back to the server in a form post!

I came across this because i was dynamically building the form and populating a database from what came back and stuff wasnt getting updated when i unticked the checkboxes.

After a lot of debugging trying to suss the problem i discovered the issue as outlined above.

Anyway to cut to the chase... the way to solve this - or at least how i solved this was to add a hidden field with the same NAME (not ID) just before the checkbox.

To set the name you will have to do a little messing about as its not a property on the server control.  My situation was unique as i had the controls on a user control so i took the UniqueID of the usercontrol, replaced the separator '_' with the ClientIDSeparator '$' and then added $checkboxname to the end.

The next thing you will have to do is remove a comma ',' from the value in the form as multiple items with the same name create an array of controls on the form that all get placed into the value.

So just strip that out and you should now get a form item with the name of the checkbox as an empty string even when the checkbox is unchecked!

Hope you understand that.  Like i said my situation was unique so i cant really drop source code in but if you need any help with your situation then add a comment and i'll try to help.