Wednesday, February 3, 2010

Using Original HTML IDs of Controls in JavaScript

One of the first problems I found went I started using JavaScript code within ASP .Net pages was that the controls from ASP.Net where at many times not directly accessible by JavaScript.

The IDs used for the controls within the ASP.Net page cannot be reliably used in JavaScript to reference that control. The reason is simple. To avoid conflicts in naming, ASP.Net automatically converts the IDs to unique IDs in HTML. These IDs generated for HTML are usually much bigger that the actual Control’s ID. This generated ID is called CllientID.

Almost all ASP.Net controls have a ClientID property. So, to get the ClientID in server code one could use:

string clientId = myControl.ClientID;

Where myControl is an ASP.Net Control.

Now the tricky part is to access this ClientID property from within JavaScript. One easy way I found to do this was to pass the ClientID of required controls at page start up. To do so, we should use ClientScript.RegisterClientScriptBlock. A sample usage:

ClientScript.RegisterClientScriptBlock(this.GetType(), "StartupScript", String.Format(@"
     var txtControlClientID = '{0}';
",
     txtControl.ClientID)
, true);

Now, in JavaScript, we access the control as:

var txtControl = $get(txtControlClientID);