如何使用< label>在ASP.NET中标记? [英] How to use the <label> tag in ASP.NET?

查看:93
本文介绍了如何使用< label>在ASP.NET中标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在ASP.NET应用程序中使用<label>标记?我希望它是有效的,可访问的和可用的.

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

我了解最佳的HTML方式是这样的:

I understand the optimal HTML way is this:

<label for="Username">Username:</label>
<input type="text" id="Username" runat="server" />

但是,如果上面的代码在ASP.NET用户控件中,则输入ID将更改,这意味着标签的"for"属性无效.我可以将label标签设置为服务器控件,并在代码(Username.ClientID)中设置其"for"属性,但是对于这种简单的事情来说似乎需要做很多工作.

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.

我也曾经看过这种HTML:

I've also seen this HTML used in the past:

<label>
    <span>Username</span>
    <input type="text" id="Username" runat="server" />
</label>

什么是正确的方法?

推荐答案

为此,我使用了<asp:Label ... AssociatedControlID="Username" ...>控件.它们被渲染为<label>标签,并适当地设置了for属性.

I use <asp:Label ... AssociatedControlID="Username" ...> controls for this. They get rendered as <label> tags and set the for attribute appropriately.

请注意,您还可以根据需要在Label控件中嵌套其他标签:

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>

这篇关于如何使用&lt; label&gt;在ASP.NET中标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆