Getting References to Objects in ASP.NET AJAX and Elsewhere

When getting references to DOM object in ASP.NET AJAX script, you can use the $get() mechanism.  $get is a shortcut for document.getElementById, and it works well, but there is something you have to understand about ASP.NET server controls.  For instance, if you have the control:

<asp:Button id="btn1" runat="server" Text="Click Me" />

In an ASP.NET page, the underlying button may render an HTML element with an ID of "btn1", but if this button is in a user control, or if there is a master page, controls have to create a client side unique name for the butto,which looks something like this:

ctl100$ContentPlaceholder$MyUserControl$btn1

Because the ID's can change, you shouldn't reference it this way.  Instead, you can leverage the server-side ClientID property to get a reference in the control.  In ASP.NET AJAX script, you can do this:

<script ..>
function pageLoad()
{
    var element = $get('<%= btn1.ClientID %>');
}
</script> 

This will return the longer ID notation to the $get method, getting the correct reference.  However, in certain code you can't do this.  For instance, I tried this approach in an onclick handler for a server control, like so:

<asp:CheckBox .. onclick="someHandler('<%= chk1.ClientID %>');" />

Onclick maps over to the client-side onclick, but does not input the ClientID, but renders the value directly.  The approach I often take is to embed it on the server-side:

function Page_Load(..)
{
    chk1.Attributes["onclick"] = "someHandler('" + chk1.ClientID + "');";
}

Published Saturday, February 23, 2008 4:18 PM by bmains
Filed under: ,

Comments

No Comments

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.