Archive for the ‘ASP.NET’ Category

ASP.NET ClientID & jQuery small trick

February 8, 2010

Up to ASP.NET 3.5 the client ids for .NET controls is not for passionate readers it looks like this: “ctl00_ctl00_decoratedArea_contentArea_homeSearch_mileageDropDownRow”
On the other hand the client name is “ctl00$ctl00$decoratedArea$contentArea$homeSearch$mileageDropDownRow” so this does not really help.

If you have to reference this from client code:
1) Migrate to asp.net 4.0 ( best option )
2) Use <%controlName.ClientID %>, but this only applies in a aspx or ascx file

If you are writing code in a js file there is no easy way, but the jquery to the resque!
Just use selector like this $(‘id$=shortServerId’)
This selects all elements which have attribute id ending with ‘shortServerId’ and returns them as array. If you want to apply non-jquery code to your selection as normal DOM functions first reference to array element of choice like this.

var allElements = $('id$=shortServerId');
if(allElements.length > 0) {
    yourDomFunciton(allElements[0]);
}

Needless to say it is a lot better to make yourself a favor and use only jQuery for  DOM modifications.

References
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx
http://weblogs.asp.net/dotnetstories/archive/2009/10/27/asp-net-4-0-and-clientid-mode.aspx