Rendering the correct label tag in your forms

You should be using combinations of <asp:Label> tags and input tags such as <asp:TextBox> in your forms.

The <asp:Label> tag is one of several controls that will render different html depending on the way you configure it. Its default is to turn into a <span> tag but in the scenario above the correct tag would be a <label> with a for="" attribute.

How do you do this? Just add the AssociatedControlID attribute to your control.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "">
<html xmlns="">
<head runat="server">
    <title>Label AssociatedControlID Example</title>
    <form id="form1" runat="server">
        <h1>Label AssociatedControlID Example</h1>
        <p>Load this page into a browser and view source to see the different html markup.</p>
        <h2>Label tag without an association</h2>
        <asp:Label ID="Label1" runat="server" AssociatedControlID="TextBox1" Text="Label" /><br />
        <asp:TextBox ID="TextBox1" runat="server" />
        <h2>Label tag with an association</h2>
        <asp:Label ID="Label2" runat="server" AssociatedControlID="TextBox2" Text="Label" /><br />
        <asp:TextBox ID="TextBox2" runat="server" />

The benefits of this technique are two-fold. Firstly by using semantic mark-up you are staying true to the intentions of web standards. Secondly you are enhancing accessibility by giving screen readers and other devices a much better chance of matching the label with the input control.

If it isn't already - this should become a standard practice in your form development technique. v1.1 and older

This feature is not supported in 1.1 and older. To be a good net citizen in those versions of .net you will have to manually create a label tag and associate the for tag using inline commands such as:

<label for="<%=TextBox1.ClientID %>">Label</label>
<asp:TextBox id="TextBox1" runat="server" />

No comments :