Using html label tags with asp.net

I am amazed to see how many asp.net programmer do not use this

The label tag is extremely useful and easy to use, it boggles my mind why more Asp.Net devs do not use it. Remember, I am talking about the html label tag, not the asp.net asp:label which produces a span.

what does it do?

Many of you probably know what it does, but many may not. Quite simply, it makes bunch of text clickable for the related form element. For example, here I am not using a label:
Click Me:

As you can see, you need to click on the textbox itself to get focus on it, clicking on 'Click Me' does nothing. Below, I am using a label tag around the title:

how do I use it?

The syntax is simple! For regular html, this is all you need to do:

<h5><label for="txt">Click Me:</label></h5>
<input id="txt" type="text" />


For asp.net markup, it's a little more, but still incredibly simple:

<h5><label for="<%= txt.ClientID %>"></label></h5>
<asp:TextBox ID="txt" runat="server" />


Notice that some inline magic had to be done to account for the sometimes crazy nested control names that asp.net can dish out. This works for any kind of form element, it's great. Some asp.net controls like CheckBox, RadioButton, etc. employ it with the 'Text' property, but controls like DropDownList, TextBox, etc. do not.

so why aren't you using it?

Make your users lives just a little easier and go wrap all of you form element titles in label tags, it's stupid not to.

EDIT: As Frederik pointed out below, you can use the asp:label if you set the AssociatedControlID which will work just as well. I just prefer to use the html label tag as it is less markup; thanks Frederik!

Comments (3) -

  • Actually you can use the label web control for this:
    <asp:Label runat="server" AssociatedControlID="txt"></asp:Label> - which will render a html label element.
  • Hi

    As Frederik already pointed out, you can use the ASP.NET Label control to render the <label> tag for you. But there is a certain advantage using the ASP.NET Label control over the standard <label> tag:

    This is when you develop multilingual sites and use the Visual Studio inbuilt "Generate Local Resource" functionality. This automatically adds entries for all [Localizable] properties into resource files (which can be easily translated). (this will not happen for standard html controls - entries into resource files won't be added, hence those pages won't be easily translated)

  • You have been a great inspiration so far.

Add comment

Loading