2010-11-14

ASP.NET - How to get client ID with jQuery

It is a while I have started using ASP.NET hand-in-hand with jQuery to enhance user experience with a web applications. Once in a while, I was forced to access client objects by only knowing server ID of the original ASP.NET Control. In other cases, you would usually manage it by passing client ID directly into a javascript code:

jQuery('#<%= TextBox1.ClientID %>');

But if you for some reason cannot use this approach, you can always search for client ID by providing its server ID.

jQuery.extend({ clientID : function (serverID) {
    if (serverID) return jQuery("#" + serverID
            + ", [id$='_" + serverID + "']").attr('id');
}});

Let's break it into pieces and see how it works.

jQuery selector above is written based on method by which ASP.NET composes client IDs. If the control we are looking for is placed in 1th level of the Control Tree, first selector will find the element.

ServerID: "TextBox1"
ClientID: "TextBox1"

Selector: jQuery("#TextBox1")

If the control would be in deeper level, second selector will be the effective one.

ServerID: "TextBox1"
ClientID: "MainContent_ctl00_TextBox1"

Selector: jQuery("[id$='_TextBox1']")

In this case, TextBox1 is placed inside FormView without explicitly set ID. This FormView is placed inside ContentPlaceHolder named "MainContent". So it means, we want to search for HTML element with ID ending with "_TextBox1".

The underscore mentioned above is crucial for correct behavior of the function. Let's say we have two controls inside ContentPlaceHolder / FormView:

ServerID1: "MyTextBox1"
ServerID2: "TextBox1"
ClientID1: "MainContent_ctl00_MyTextBox1"
ClientID2: "MainContent_ctl00_TextBox1"

Selector used: jQuery("[id$='TextBox1']")

This time we are trying retrieve client representation of "TextBox1", but query will result in two different elements. Since .attr() returns value of an attribute for the first element in the set of matched elements, we will get "MainContent_ctl00_MyTextBox1", instead of "MainContent_ctl00_TextBox1".

Usage:

var serverID = 'TextBox1';
var clientID = $.clientID(serverID);
// Displays something similar to "MainContent_ctl00_TextBox1"
alert(clientID);

Personally I use this extension combined with some other 3rd party JS libraries, otherwise more useful extension would be:

jQuery.extend({ aspControl: function (serverID) {
    if (serverID) return jQuery("#" + serverID
            + ", [id$='_" + serverID + "']");
}});

which returns jQuery object representing matched element, instead of its ID as string value.

No comments:

Post a Comment