02 October, 2009

Access C#.NET Server controls by id on client side

In C#.NET, when you declare a Control runat="server", the id of the Control is not the same on the client side.

For example, a Control named "browserWidth" on the server side will have the following id on the client side : "ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_browserWidth".

Thus, you can't access it with a classic Javascript $("browserWidth"), and it is very difficult to guess what client id the Control will have.

My best hack for that is to use the "class" attribute, that can be multiple, and add a class which name is the same as the id of the Control, like this : class="browserWidth" or CssClass="browserWidth" if you work with an asp.net Control.

This way, I can access my client control with Javascript $$("*.browserWidth")[0].

The only problem comes with the asp:HiddenField Control that doesn't accept CssClass attribute.

On the client side, I have a tricks to access to it :

$$('input').where(function() { return (this.id.indexOf("browserWidth") != -1); })

The "where" fucntion is one of mine explain in the next Post.

This tricks works under two conditions :

- your Control has a unique ID
- the Server ID of the Control is contained in the client ID "ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_browserWidth"

If M$ changes the way client ID are made and decides to not add server control id at the end, that tricks would not work.

No comments: