This post explains about setting the client ids in ASP.NET 4.0. Knowing the id attribute of the control rendered on page is a long-standing issue. It is important to know the id if we want to use it in script libraries. The new property ClientIdMode Addresses this issue.
The id attribute for Web Server controls is generated based on the ClientId property of the control. The algorithm uses clientid property and concatenates it with naming container. In case of repeater and data source controls it adds prefix and sequence number. This algorithm always guarantees that the generated IDs are unique in the page.
The resulted IDs from the algorithm were not predictable and were therefore difficult to reference in client script.
The new ClientIdMode property allows you to specify more precisely how the client ID is generated for controls. Possible Settings are the following:
- Legacy â€“ Equivalent to ClientID property behavior of earlier ASP.NET versions.
- Static – When you set this property the id renders as-it-is. No matter what naming container the control is in. This option gives you more control over the ID, but is the least safe.
- Predictable â€“ This option is for use in data controls which use repeating templates. The generated donâ€™t have the names that contain strings like â€œctlxxxâ€. Only user-defined ID will be included in the resulting control ID.
- Inherit – This setting is default behavior for controls. It specifies that controlâ€™s ID generation is the same as its parent.
Setting the ClientIdMode property at page level.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ClientIdMode="Predictable" %>
The above declaration defines the default value for all controls on current page.
Setting the ClientIdMode property at application level
<system.web> <pages clientIdMode="Predictable"></pages> </system.web>
The above declaration defines the default value for all controls in all pages in the application.
If you want to reduce the length of the rendered ids in page then you have to set the ClientIdMode property to static as shown in below
<tc:NamingPanel runat="server" ID="ParentPanel" ClientIdMode="Static"> <tc:NamingPanel runat="server" ID="NamingPanel1" ClientIdMode=â€Predictable"> <asp:TextBox ID="TextBox1" runat="server" Text="Hello!"></asp:TextBox> </tc:NamingPanel> </tc:NamingPanel>
In the above sample, Outermost panel set the ClientIdMode property value to â€œstaticâ€ and inner panel set the property value to â€œPredictableâ€. These settings yields the following markup.
<div id="ParentPanel"> <div id="ParentPanel_NamingPanel1"> <input name="ctl00$ContentPlaceHolder1$ParentPanel$NamingPanel1$TextBox1" type="text" value="Hello!" id="ParentPanel_NamingPanel1_TextBox1" /> </div>
|Share this post :|