/ Published in: C#
Because of master pages C# changes your id's to make them unique. This allows you to place your javascript in a seperate .js file or just get rid of a document.getElementById('');type solution
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/*place in app_code to use throughout your site:*/ /// <summary> /// setup cGET for all Page Controls /// </summary> public static void setup_cGET(Page page) { setup_cGET(AllControls(page), page); } /// <summary> /// setup cGET for all items in your control /// </summary> public static void setup_cGET(Control c, Page page) { setup_cGET(AllControls(c), page); } /// <summary> /// setup cGET for passed Controls ex. setup_cGET(txtbox1, txtbox2...); /// </summary> public static void setup_cGET(Page page, params Control[] wc) { if (wc.Length > 0) { for (int i = 0; i < wc.Length; i++) { r.Add(wc[i]); } setup_cGET(r, page); } } /// <summary> /// Setup a javascript cGET function that looks up controls. This solves the problem of not knowing the id in c# master pages /// Can only run this function once, should be using a scriptmanager /// </summary> /// <param name="c"></param> public static void setup_cGET(List<Control> lc, Page page) { if (lc.Count <= 0) return; // Now loop through the controls and build the client and server id's string js = "var cGET_serverIDs = new Object();"; foreach (Control c in lc) { if (c.ID != null && c.ID.Length > 0) js += "cGET_serverIDs['" + c.ID + "'] = '" + c.ClientID + "';\n"; } // Now register the method GetClientId, used to get the client id of tthe control ScriptManager.RegisterStartupScript(page, page.GetType(), "cGET", js+ "function cGET(serverId) " + " { " + " if (cGET_serverIDs[serverId] != null) " + " return document.getElementById(cGET_serverIDs[serverId]); " + " " + " return document.getElementById(serverId);" + " } " , true); } /// <summary> /// Loads all controls recursively. /// </summary> /// <param name="container">The container to search for the control passed. Remember /// all controls (Panel, GroupBox, Form, etc are all containsers for controls /// </param> /// <returns></returns> private static List<Control> AllControls(Control container) { foreach (Control ctrl in container.Controls) { foreach (Control c in AllControls(ctrl)) r.Add(c); } r.Add(container); return r; } /* on each page */ protected void Page_Load(object sender, EventArgs e) { GlobalFunction.setup_cGET(Form, this); } /*.js file */ cGET('textBoxID').value = '5';