Tagged: Replace Server Tags

Gettting ClientIDs of asp.net controls in an external javascript file

When maintaining external javascript files for our webpages the biggest hurdle we face is the getting clientID of our server side controls in the javascript file. Let me demonstrate a workwround for this that I usually adopt.
Step 1:
In the page load event create an array of json objects representing the clIentIDs of all the controls that we would be requiring to use in javascript functions. Store this in a javascript global variable using window::onload function.

private void SaveControlClientIDs()
    System.Text.StringBuilder ctlObj = new System.Text.StringBuilder();
    ctlObj.Append("{""Id"":'" + ddlEmployee.ClientID & "',""Type"":'" + ddlEmployee.GetType().ToString() + "',""DefaultValue"":'0'},");
    ctlObj.Append("{""Id"":'" + txtName.ClientID & "',""Type"":'" + txtName.GetType().ToString() + "',""DefaultValue"":''},");
    ctlObj.Append("{""Id"":'" + txtEndDt.ClientID & "',""Type"":'" + txtEndDt.GetType().ToString() + "',""DefaultValue"":''}");
    string bodyOnloadScript = "<script type='text/javascript'>function body_onload() { ctlIds=" + ctlObj.ToString() + ";}</script>";
    Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", bodyOnloadScript);

Step 2:

In your javascript file use the following function to retrieve the clientID using the actual id of your control

var ctlIds; //this is the global variable which will store the json objects
function GetCtlClientId(id) {
    var arr = ctlIds;
    var res = ”;
    var i = 0;
    for (i = 0; i < arr.length; i++) {         if (arr[i].Id.indexOf(id) != -1) {             res = arr[i].Id;             break;         }     }     return res; } [/sourcecode] In .NET 4.0 the issue of ClientIDs has been addressed to an extent. Till you move to 4.0 hope this helps:-)