Making checkboxes always post a value in an HTTP request

| No TrackBacks

I've been working on an ASP.NET MVC project with a nice and fancy model layer. My models have a nice'n'friendly UpdateFrom(NameValueCollection) method to bind HTTP request parameters to an object. The only problem is that sometimes, I don't want to have every column on a form, and some of the related database columns should remain unchanged.

In HTML forms, this presents a problem: checkboxes that are unchecked don't post anything. How am I to tell if a field has been left off the form or if a field is unchecked? After some aimless wanderings on the inter-tubes, I found this article which documents a solution for Rails.

It's pretty simple, so I figured I would take this idea and wrap it up in a server control. We have a small set of server WebControls that play nice with the rest of our code, so it was just a matter of adding a few lines of code. You could also wrap this up in a helper method like in the rails version.

CheckBox checkbox = new CheckBox();
checkbox.InputAttributes.Add("class", CssClass);
checkbox.InputAttributes.Add("id", (string.IsNullOrEmpty(ID) ? (FieldName + "CheckBox") : ID));
checkbox.InputAttributes.Add("value", "true");
checkbox.InputAttributes.Add("onclick", 
    "document.getElementById(\"" + FieldName + "TextBox\").value = this.checked.toString()");
checkbox.Checked = Checked;
checkbox.RenderControl(writer);

TextBox textbox = new TextBox();
textbox.Attributes.Add("style", "display: none;");
textbox.Attributes.Add("id", FieldName + "TextBox");
textbox.Attributes.Add("name", FieldName);
textbox.Text = Checked ? "true" : "false";
textbox.RenderControl(writer);

Now I can tell if a checkbox field is truly meant to either just not be there or is false.

No TrackBacks

TrackBack URL: http://www.sagecraft-studios.com/mt-tb.cgi/6