When I create a form, I try to make accessibility a top priority, but the output from asp .NET negates some of this. For example, when I set a label tag for an input tag, I create it a such:
<label for="frmFirstName">First Name<span class="required">*</span></label>
<asp:TextBox id="frmFirstName" CssClass="textbox" runat="server" />
But, when the HTML is output from the page, it is output as:
<label for="frmFirstName">First Name<span class="required">*</span></label>
<input name="ctl00$phMainContent$frmFirstName" type="text" id="ctl00_phMainContent_frmFirstName" class="textbox" />
This is a problem, as now the label is no lo开发者_JAVA百科nger tied to the input element. Is there a way to force .NET to output the exact id I set for the input field? I shouldn't have to use Javascript to correct something like this.
If you use ASP.Net 4 you can set the ClientIDMode attribute of the control to static
. This will let it keep the value of the ID tag when rendered.
Use the asp:Label
element and point its AssociatedControlId
property to your textbox.
<asp:Label ID="lblFirstName" runat="server" AssociatedControlId="frmFirstName">First Name<span class="required">*</span></asp:Label>
<asp:TextBox id="frmFirstName" CssClass="textbox" runat="server" />
That should output the correct HTML for you.
In addition to the AssociatedControlId and <%= control.ClientId %> solutions, if your control (in this case, "frmFirstName") is guaranteed to be the only control with that ID on the page, then you can set the ClientIDMode property of the control to "Static", which will mean that ASP.NET will not munge the ID in the rendered HTML.
For example:
<label for="frmFirstName" runat="server" ID="lblFirstName">First Name</label>
<asp:TextBox runat="server" ID="frmFirstName" ClientIDMode="Static" />
will render as
<label for="frmFirstName" id="some$aspnet$id$lblFirstName">First Name</label>
<input type="text" id="frmFirstName" />
This will also make it easier if you happen to need to refer to it from Javascript, since it can be a pain to render ASP.NET's auto IDs in Javascript (as far as I know, it's impossible to do in a seperate .js file, you'd need to embed the JS on the page and use <%= control.ClientID %>).
See more about ClientIDMode here: http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx
You can use the ClientId
property. This is what will be output as the control Id in HTML and what you can use client side to reference the rendered element:
<label for="<%:frmFirstName.ClientId%>">First Name<span class="required">*</span></label>
<asp:TextBox id="frmFirstName" CssClass="textbox" runat="server" /
Note:
<%:%>
is new with ASP.NET 4.0 - you will need to use <%=%>
if on .NET 3.5 and before.
Edit:
Just to add that ClientId
is the way to go when referencing the control from Javascript.
精彩评论