When to use asp:Label

In yesterday’s post, “asp:label or asp:literal” I encouraged the use of <asp:literal> instead of <asp:label> because it outputs cleaner HTML. So when is it appropriate to use <asp:Label>?

When you use the “AssociatedControlID” attribute in <asp:Label>, it will output a <label> tag in HTML, rather than the <span> tag it normally outputs. This is useful when you are associating text to an input field of a form as shown in “Forms with CSS (1 of 3) – HTML Markup“. Consider the following two pieces of ASP.NET code:

<asp:Label AssociatedControlID="txtTest" runat="server">Test:</asp:Label>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>

and

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

Both output the exact same HTML code as shown here:

<label for="ctl00_MainContent_txtTest">Test:</label>
<input name="ctl00$MainContent$txtTest" type="text" id="ctl00_MainContent_txtTest" />

While both pieces of sample code above output the same HTML, I haven’t decided which way I prefer. I’m thinking the one using the <asp:Label> tag might have more semantic meaning, which should make it easier to maintain in the long run.

Advertisements

1 comment so far

  1. […] (Dec 18, 2008): Added link to When to use asp:Label ] Possibly related posts: (automatically generated)When to use asp:LabelLabeling HTML Form […]


Comments are closed.

%d bloggers like this: