Using the HTML label element with ASP.NET

by Justin 1. May 2008 00:28

You've probably noticed that a <asp:Label /> element actually renders a <span> tag, not the <label for="name"> tag that's been around since HTML 4. Luckily, it's pretty easy to include the label element in your ASP.NET forms.

ASP.NET 2.0, 3.0, 3.5 and Later

To make the <asp:Label /> control render as a <label> instead of a <span> include the AssociatedControlID attribute like so.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
	<title>Untitled Page</title>
</head>
<body>
	<form id="form1" runat="server">
		<asp:Label ID="Label1" runat="server" AssociatedControlID="TextBox1" Text="Label"></asp:Label>
		<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
	</form>
</body>
</html>

 

ASP.NET 1.0, 1.1

Unfortunately, older versions of ASP.NET don't support the AssociatedControlID attribute. Instead, you'll have to create a regular HTML <label> element and manually write out the ID of the associated control in the "for" attribute. 

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="test.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
	<title>WebForm1</title>
	<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
	<meta name="CODE_LANGUAGE" Content="C#">
	<meta name="vs_defaultClientScript" content="JavaScript">
	<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
	<form id="Form1" method="post" runat="server">
		<label for="<%=TextBox1.ClientID %>">Label</label>
		<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
	</form>
</body>
</HTML>

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen