views:

2729

answers:

5

What is the best way to use the <label> tag within an ASP.NET application? I want it to be XHTML valid, accessible and usable.

I understand the optimal way is this:

<label for="Username">Username:</label>
<input type="text" id="Username" runat="server" />

But if the above code is in an ASP.NET user control, the input ID will change, meaning the label's "for" attribute is useless. I could make the label tag a server control and set it's "for" attribute in the code (Username.ClientID) but it seems like a lot of work for such a simple thing.

I've also seen this HTML used in the past:

<label>
    <span>Username</span>
    <input type="text" id="Username" runat="server" />
</label>

What is the optimal approach?

+10  A: 

I use <asp:Label ... AssociatedControlID="Username" ...> controls for this. They get rendered as <label> tags and set the for attribute appropriately.

Note that you can also nest other tags within the Label control if you wish:

<asp:Label ID="UsernameLabel"
           Text="Username:"
           AssociatedControlID="UsernameTextBox"
           runat="server">
    <asp:TextBox ID="UsernameTextBox" runat="server" />
</asp:Label>
Sean Bright
I too use this approach but always set EnableViewState="False" for the label tag, particularly if it is a substantial form. The smaller the viewstate the better in my opinion.See http://stackoverflow.com/questions/113479/when-to-enable-disable-viewstate
Jon P
Agreed. It was left out for brevity.
Sean Bright
I find it easier to turn ViewState off in Web.Config page settings and turn it on on only the controls you need it for. Yes, ViewState really adds up and slow things down if you just leave it on for all controls.
Brian Kim
+4  A: 

use the <asp:Label> server control. It has a property that you can use to set the associated control ID.

<asp:Label ID="label1" runat="server" Text="Username" AssociatedControlID="Text1" />
<asp:TextBox ID="Text1" runat="server" />
Matt Brunell
+4  A: 

I guess the easiest way to do it is this.

<asp:Label AssociatedControlID="Username" runat="server" Text="Username:"></asp:Label>
<asp:TextBox ID="Username" runat="server"></asp:TextBox>

EDIT: Wow.. all same answers within a minute. =)

Brian Kim
A: 
<p><asp:Label ID="label1"           Text="Username:"           AssociatedControlID="txtUserName"           runat="server">    <asp:TextBox ID="txtUserName" runat="server" /></asp:Label></p>
chugh97
A: 

You can also write it like this:

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

Phil Haack has a blog post on this topic

Christian Hagelid