Brian Mains

Catch me on linked in at:, or follow me on twitter at: @brianmains.

AJAX Controls and ClientIDMode

The new ClientIDMode property is a new .NET 4.0 features that allows a developer to take control over the ClientID property.  In .NET 3.5 and earlier, the ClientID property renders in the ID HTML attribute for all controls.  The system generated ID would be very long, may be looking something like ct100_ct100_BOdyPlaceholder_Ctl for a control that has an ID property of Ctl, and as such, ClientIDMode gives you much better control over this rendering process.  For instance, a mode of Static takes whether the ID value is and renders it directly, which is very useful but potentially dangerous (as then you have to ensure that each ID is unique).  It seems a lot of people favor the Predicable, trimming down the "ID fat."  ClientIDMode can be set per control, in the @Page declaration, and in the config file.

From an AJAX perspective, this can be helpful.  It was mostly required to find an AJAX control (especially if the application used a master page).  This required these types of lookups of AJAX components:

var control = $find("<%= Button1.ClientID %>");

This finds a button AJAX control, but as you can see, because the ID is never the same as the ClientID, we needed to render it from the server-side so that the correct client-side ID (always ClientID) is passed in and the control is properly found.

But with the addition of ClientIDMode, for controls we know are standard, we can define a control like:

<nucleo:Button id="b1" runat="server" ClientIDMode="Static" />

And can reference it on the client as:

var control = $find("b1");

Because both the ID and the ClientID match on the server, thus the server-side ID of b1 is also the client side ID of b1, and it makes it easier for lookups, though the previous approach wasn't that much more difficult.  There are only a handful of scenarios where the <%= %> syntax doesn't work, such as templated controls that are not marked with [TemplateInstance(TemplateInstance.Single)] attribute definition, or repeating templates.  The syntax must also be specified in the same container (same page, same user control, etc.).

I'd recommend using ClientIDMode="Static" for central controls, such as the scriptmanager, or if you use Telerik the RadAJaxManager and other Rad manager controls.  Additionally, other master page controls can use a static ID, and then it makes it easier to target these controls from client-side JavaScript, as we don't have to mess around with the <%= control.ClientID %> syntax and any general scoping issues that may bring.

There is an AJAX benefit to the new ClientIDMode property.

Posted: Tue, Nov 16 2010 20:22 by bmains | with no comments
Filed under: ,
Leave a Comment





If you can't read this number refresh your screen
Enter the numbers above: