Friday, 1 April 2011

How to get Asp.net Control ClientID in external javascript file

Every asp.net developer knows that Every control which is running at server in asp.net application changes the id of the control while rendering into the browser. If it is an Internal script we can access using '<%=ConrolId.ClientID>'. But we cann't access like this in external javascript file.

Solution to access the Serverside control in External javascript file:

Step1:We need to declare two arrays; the first array will have the server IDs of the required controls, and the  second array will have the client IDs of the server controls in the same order.

Step2: Register these two arrays at the client side.

Step3:Now, create a JavaScript function which will accept the server ID and will compare the server ID with the available server IDs in the array and will give its position in the array. Then, the same function would return you the matching client ID from the same location in the client IDs array.

The code below shows the declaration of the array, and the declaration of the JavaScript function in the code-behind.
/* This is the method used to register the array
of the clientid's as well as the serverid's
Also this method registers the function GetClientId, which is used
to get the client id provided server id is supplied */

public void RenderJavaScriptArrayWithCliendIds(params Control[] wc)
{
if (wc.Length > 0)
{
StringBuilder arrClientIDValue = new StringBuilder();
StringBuilder arrServerIDValue = new StringBuilder();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;

// Now loop through the controls and build
//the client and server id's
for (int i = 0; i < wc.Length; i++)
{
arrClientIDValue.Append("\"" +
wc[i].ClientID + "\",");
arrServerIDValue.Append("\"" +
wc[i].ID + "\",");
}

// Register the array of client and server id to the client
cs.RegisterArrayDeclaration("MyClientID",
arrClientIDValue.ToString().
Remove(arrClientIDValue.ToString().Length - 1, 1));
cs.RegisterArrayDeclaration("MyServerID",
arrServerIDValue.ToString().
Remove(arrServerIDValue.ToString().Length - 1, 1));

// Now register the method GetClientId,
// used to get the client id of tthe control
cs.RegisterStartupScript(this.Page.GetType(), "key",
"\nfunction GetClientId(serverId)\n"+
"{\nfor(i=0; i<MyServerID.length; i++)" +
"\n{\nif ( MyServerID[i] == serverId )\n" +
"{\nreturn MyClientID[i];\nbreak;\n}\n}\n}", true);
}
}

Call the method in BasePage or BaseMaster which is accessible to all the pages
RenderJavaScriptArrayWithCliendIds(tbUserName[,tbpassword,.......]);

In the external javascript file if u want to get the clientid of tbUserName then call the javascript function as follows
var tbUserName=document.getElementById(GetClientId('tbUserName'));

This will solve any issue arising due to changes in the client IDs of controls placed inside a Master Page or Page.

No comments:

Post a Comment