Semantic CheckBoxList & RadioButtonList
(
May 08 2007 - 09:37:52 PM by
Timothy Khouri) - [
print article]
Quick Semantics Lesson
In an earlier article (Making Your Own Semantic Controls) we talked about how HTML tags should have a "meaning", and should define your content. An <ol> tag describes an ordered list of items, such as your "top 10 favorite sites." Because that list is in a specific order, you would use the <ol> tag. A <ul> tag describes an un-ordered list of items, such as your site's navigation links, or as in the case with this article, a list of radio buttons or checkboxes.
The purpose of using semantic HTML is to seperate your "content" from your code. HTML tags are used to tell a web browser, an audio browser or a search engine bot exactly "what" your content is. The problem with developers, especially old-school web designers, is that they rely on HTML tags to make something look pretty. This creates ugly markup, and nearly worthless content. So we are going to now discuss how we can very easily create our own SemanticCheckBoxList and SemanticRadioButtonList controls. They will render their list items to <ul> and <li> tags. This will not only make sense, but it will also allow for easy styling with CSS.
Let's jump right into the code. I'll explain what we are doing through C# comments.
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public class SemanticCheckBoxList : CheckBoxList
{
}
So far this is very easy. We just need a few namespaces to get our classes from; the System.Web.UI namespace to get the HtmlTextWriter class from, and the System.Web.UI.WebControls namespace to get our CheckBoxList or RadioButtonList class to inherit from. We'll now look at the one simple method we need to override.
protected override void Render(HtmlTextWriter writer)
{
writer.WriteBeginTag("ul");
if (this.CssClass.Length > 0)
{
writer.WriteAttribute("class", this.CssClass);
}
writer.Write(">");
for (int i = 0; i < this.Items.Count; i++)
{
writer.WriteFullBeginTag("li");
this.RenderItem(ListItemType.Item, i, new RepeatInfo(), writer);
writer.WriteEndTag("li");
}
writer.WriteEndTag("ul");
}
This took very little code, but the results are very nice. We now have a semantic CheckBoxList and RadioButtonList class. Nothing has changed except for how it renders. Here is the ASP.NET code that you would use to create our new control.
<SingingEels:SemanticCheckBoxList ID="ExampleCheckBoxList" runat="server">
<asp:ListItem Value="One" Text="One" />
<asp:ListItem Value="Two" Text="Two" />
<asp:ListItem Value="Three" Text="Three" />
</SingingEels:SemanticCheckBoxList>
Soon I'll show you how you can make your semantic controls using ASP.NET Control Adapters instead of inheriting from the control and changing it right in the Render method.