Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the <label> tag in ASP.NET?

How can I use the <label> tag within an ASP.NET application? I want it to be valid, accessible, and usable.

I understand the optimal HTML 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 its "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 proper approach?

like image 912
Alex York Avatar asked Jan 29 '09 22:01

Alex York


People also ask

How do I add a label in webform?

To add a Label Web server control to a Web Forms pageFrom the Standard tab of the Toolbox, drag a Label control onto the page. In the Appearance category of the Properties window, set the control's Text property to the text to display.

What is HTML LabelFor?

The <label> HTML element represents a caption for an item in a user interface.


2 Answers

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> 
like image 144
Sean Bright Avatar answered Sep 21 '22 13:09

Sean Bright


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

like image 30
Christian Hagelid Avatar answered Sep 21 '22 13:09

Christian Hagelid