ASP.NET Essentials - The Label
Tuesday, June 19 2007 0 Comments
After talking to developers for a few days about basic HTML and ASP.NET topics, I find that I always focus on the Label control.
More specifically, I’m talking about the <label> tag in HTML. What does this tag do? Why should we care, when we can just write the text before an input control on the page?
For starters, the label has semantic meaning. The <label> tag gives meaning to a textbox or a dropdown. If you were blind and browsing using a screen reader, you’d appreciate the little semantic tidbits that give you an easier browser experience.
Another benefit is that we can select and style the label easily, making the transition to table-less forms so much easier.
A third and possibly more useful benefit is that the mouse stays as a pointer, and clicking on the text sets the focus to the corresponding control.
The usage in standard HTML is like this:
<label for='user_name'>User Name:</label><input type='text' id='user_name' />
(notice how the mouse cursor stays as a pointer, instead of the standard text cursor)
If you were a reasonable person, you’d think that the <asp:label> control would render as an HTML <label>, but you’d be wrong. ASP.NET renders a standard <asp:label> as a <span>. ASP.NET 2.0 fixed this, however you have to specify the AssociatedControlID property to change the rendering behavior.
This leads me to another point that I’d like to make with the Label control. Often times we just want a static label, like in the example above. If we use the <asp:label> then we’ll have a server-side component as well and a viewstate hit.
We certainly don’t need viewstate in this scenario, Often times we just neglect these things until they are a problem.
I can hear you say it now… “but Ben, you can disable Viewstate by specifying EnableViewState=’false’ “… I know you can. But it’s too easy to just leave it as is. There’s also an easy alternative.
You can accomplish the same rendering without the viewstate issue by just typing this:
<label for='<%= txtUsername.ClientID %>'>User Name:</label>
This will render the same way, but also ensure that we get the generated ID of the control that we are associating with. This will not have any server-side component or any correlation to ViewState, and it is actually less characters to type.
Hope you find this information useful!

