Registering a client-side script in ASP.NET is normally done with the Page.RegisterClientScript or Page.RegisterClientScriptInclude. Both of these add the appropriate script reference into the resulting body of the HTML. However there are times when it is nice to have the script added to the head section of the page. I have written two extension methods to accomplish the task using the same naming convention as the Microsoft provided functions.
/// <summary> /// Registers the client script include in the head section. If the /// same ID is sent, the source file is replaced with the new one. /// </summary> /// <param name="page">The page.</param> /// <param name="id">The control ID to make sure there aren't two /// registered under the same ID</param> /// <param name="src">The file name.</param> public static void RegisterHeadClientScriptInclude(this Page page, string id, string src) { HtmlGenericControl si = null; foreach (Control c in page.Header.Controls) { if (c.ID != id) continue; si = (HtmlGenericControl) c; break; } if (si == null) { si = new HtmlGenericControl { ID = id, TagName = "script" }; si.Attributes.Add("type", "text/javascript"); si.Attributes.Add("src", src); } else { si.Attributes["src"] = src; } page.Header.Controls.Add(si); } /// <summary> /// Registers the client script code block in the head section of the page. /// </summary> /// <param name="page">The page.</param> /// <param name="id">The id.</param> /// <param name="code">The code.</param> public static void RegisterHeadClientScriptBlock(this Page page, string id, string code) { HtmlGenericControl si = null; foreach (Control c in page.Header.Controls) { if (c.ID != id) continue; si = (HtmlGenericControl)c; break; } if (si == null) { si = new HtmlGenericControl { ID = id, TagName = "script" }; si.Attributes.Add("type", "text/javascript"); } si.InnerText = code; page.Header.Controls.Add(si); }
Please comment if you find it interesting or crap, I would like to know either way.