Problem In ASP.NET each control has its unique ID. The control ID remains as it is until it is placed directly under “form” tag. But it is not practical . Our control may needed to placed inside a GridView which in turn placed under Update Panel which is in the Master Page. Now the format of the control ID (say “lblContact” ) is changed and looks something like : #Ctl001_ContentPlaceHolder_MyScriptManager_MyGrid_lblContact –> ASP.Net renamed the controls in special format . –> When we need to write any client side script(Javascript) we need to know the exact renamed ClientID to use the server control. Eg :document.getElementById(“#Ctl001_ContentPlaceHolder_MyScriptManager_MyGrid_lblContact“); –>Condition is worse when we want to change the name of one of the control say changing “MyGridView” to “YourGridView”. None of the client script will work containing the reference of “GridView1”. |
Solution ASP.NET Provides the feature to solve the problem by registering thejavascript array(arrName) with String of Server IDs(arrValue). So that controls can be used in client side with same ID as that of Server ID. This is possible with : void ClientScriptManager.RegisterArrayDeclaration(StringarrName,String arrValue); Implementaion We have a class to do the above task . |
public class RegisterServerIdToClientId { Page myPage; // Declare the Page object to point to the required page. public RegisterServerIdToClientId(Page myPg) { this.myPage = myPg; } #region Method for register JavaScript array with Client ID // 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 RenderJSArrayWithCliendIds(params Control[] controls) { if (controls .Length > 0) { StringBuilder arrClientIDValue = new StringBuilder(); StringBuilder arrServerIDValue = new StringBuilder(); // Get a ClientScriptManager reference from the Page class. ClientScriptManager scriptManager = myPage.ClientScript; // Now loop through the controls and build the client and server id's for (int count = 0; count< controls.Length; count++) { arrClientIDValue.Append("\"" + controls[count].ClientID + "\","); arrServerIDValue.Append("\"" + controls[count].ID + "\","); } // Register the array of client id to the client. The array is accessible to client side scriptManager.RegisterArrayDeclaration("MyClientID", arrClientIDValue.ToString().Remove(arrClientIDValue.ToString().Length - 1, 1)); // Register the array of server id to the client The array is accessible to client side scriptManager.RegisterArrayDeclaration("MyServerID", arrServerIDValue.ToString().Remove(arrServerIDValue.ToString().Length - 1, 1)); // Now register the method GetClientId, used to get the client id of the control scriptManager.RegisterStartupScript(myPage.GetType(), "key", "\nfunction GetClientId(serverId)\n{\nfor(i=0; i