How to use label for in an ASP.Net webform?

北战南征 提交于 2019-12-09 07:27:02

问题


I get this as pure HTML:

<label for="txtPais">Pais:</label>    
<input name="ctl00$ContentPlaceHolder1$txtPais" type="text" id="ctl00_ContentPlaceHolder1_txtPais" class="textInput" />

In my actual code in Visual Studio I have this:

<label for="txtPais">Pais:</label>    
<asp:TextBox ID="txtPais" runat="server" CssClass="textInput"></asp:TextBox>

How would I apply a label for this textbox?


回答1:


You should use the <asp:Label...> as detailed in this blog post on Haacked

<asp:Label id="label" AssociatedControlId="txtPais" Text="Pais:" runat="server" />
<asp:TextBox id="txtPais" runat="server" CssClass="textInput" />

This should convert correctly with the ID being converted.




回答2:


It is recommended to wrap some inputs inside of labels for accessibility (See this example).

<asp:Label ID="UsernameLabel"
           Text="Username:"
           AssociatedControlID="UsernameTextBox"
           runat="server">
    <asp:TextBox ID="UsernameTextBox" runat="server" />
</asp:Label>

I got this answer from the post that, as it happens is mentioned in a comment in the original question.




回答3:


For other people who landed here with the same google search as me... The "for" attribute in label tag helps people with accessibility tools, like screen readers, to know what text box the label is for.



来源:https://stackoverflow.com/questions/3489512/how-to-use-label-for-in-an-asp-net-webform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!