When you’re referencing a server control in JavaScript, you can’t use the designated server-side ID. Frequently, the corresponding ClientID that’s generated at runtime is different than the server-side ID, depending on its containers. For generic JavaScript routines, you need a solution to simplify this behavior.
Here’s a basic example of the problem:
<p><asp:Label ID="Label1" runat="server" /></p>
<p>ClientID of MyLabel is: <%=Label1.ClientID %></p>
In this situation a control ID will be autogenerated by default and will be similar to this markup:
<span id="ctl00_Body_MyLabel"></span>
The ID is composed by concatenating the different container IDs: ctl000 is the page ID, Body is the ContentPlaceHolder ID, and Label1 is the real control ID.
It’s clear that the ID will vary, depending on the final hierarchy of controls in the page. This behavior isn’t flexible for our client-side code. To take care of this problem, ASP.NET 4.0 introduces a new property, called ClientIDMode.
Let’s change our previous snippet to include the following one:
<p><asp:Label ID="Label1" runat="server" ClientIDMode="Static" /></p>
Now the value will be rendered differently:
<span id="Label1"></span>
As you can imagine, the ClientIDMode property is helpful when you’re dealing with JavaScript code or you need to enforce CSS in specific scenarios. Note that the name attribute isn’t influenced by this property and remains the same, as in this example of an <input /> tag:
<input name="ctl00$Body$MyName"type="text" id="MyName" />
You can use the ClientIDMode property whenever you need to take full control of the real IDs that are generated at runtime, with no limitations. AutoID is the default value for pages and Inherit is the default for controls. Your pages and controls will behave
0 comments:
Post a Comment