可以使用Label控件来标注一个HTML表单字段。Label控件拥有属性AssociatedControlID,可以设置此属性来指向表示表单字段的ASP.NET控件。
例如,代码清单2-3中的页面含有一个简单的表单,表单包含两个字段用于输入名和姓。Label控件用于标注这两个TextBox控件。


<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Label Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblFirstName" Text="First Name:" AssociatedControlID="txtFirstName"
runat="server" />
<br />
<asp:TextBox ID="txtFirstName" runat="server" />
<br />
<br />
<asp:Label ID="lblLastName" Text="Last Name:" AssociatedControlID="txtLastName" runat="server" />
<br />
<asp:TextBox ID="txtLastName" runat="server" />
</div>
</form>
</body>
</html>
为Label控件提供AssociatedControlID属性后,Label控件将呈现成HTML <label>标签而不是HTML <span>标签。在浏览器中选择查看源代码,可以看到代码清单2-3中的第一个Label控件在浏览器中生成下面这样的内容:
<label for="txtFirstName" id="lblFirstName">First Name:</label>
始终使用带有AssociatedControlID属性的Label控件来标注表单字段,对于残障人士能够访问网站很重要。如果有人使用的是像读屏器这样的辅助设备来与网站交互,AssociatedControlID属性将帮助辅助设备正确地把标签和表单字段关联起来。
使用AssociatedControlID属性的另一个好处是,当点击标签时,自动把表单焦点设置为关联的表单输入框。
注解: Web标 WCAG 1.0和508辅助功能手册都要求使用<label for>标签来标注表单字段。更多信息请访问http://www.w3.org/wai和http://www.Section508.gov。
摘自《ASP.NET 2.0揭秘》