public Blog<BenR>

Ben Reichelt's Blog

<December 2008>
SuMoTuWeThFrSa
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910


Navigation

Blogs

Subscriptions

Post Categories



Monday, January 03, 2005 - Posts

Updates, Inserts, and checkboxes

When we were developing our data access objects, we added an Update, and an Insert method, with the corresponding signatures:

Update(System.Collections.Specialized.NameValueCollection form);
Insert(System.Collections.Specialized.NameValueCollection form);

These methods take advantage of the fact that when you post a form, the form values are contained in a NameValueCollection object, so you can loop through the elements of the form, and update the respective data fields, and then update (or insert) the database with the new values.

This scheme is really convenient for when you want to add or remove items from the form, because you can simply remove them from the html, without even worrying about the backend, because those added or removed form elements are inconsequential to the workings of the code behind.  You could have a form that contained none of the data fields, and still call these methods without any problem.

The only problem arises when you need to deal with checkboxes.

If the user checks the checkbox, the value of the checkbox gets submitted and the data object can be updated with the checkbox value. However, suppose the checkbox is initially checked, and the user unchecks the checkbox.  Now, when the form is submitted, it appears as though the checkbox never existed, because it will not be present in the NameValueCollection, and the data object does not know to update the appropriate value.  We typically use checkboxes to denote true/false or 1/0 values in the database, so if a user were to leave a checkbox unchecked it means that the database value should be false or 0, but since there is no form value present, the data object does nothing to that field.

What we did to work around this problem, was to add a hidden form element to our forms.  This hidden field is a comma separated list of all the form elements that exist on the form.  This hidden field gets submitted with the rest of the form, and as the data object loops the form elements, it records them. When the looping is finished, it compares the list of form elements that it found, to the comma separated list that was submitted with the form.  If there are any form elements in the list, that were not included in the form, then the data object knows that a checkbox was left unchecked, and can then update the field accordingly.

posted Monday, January 03, 2005 10:49 PM by reic0113




Powered by Dot Net Junkies, by Telligent Systems