This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.
Howto: Add JavaScript inside Head element from code behind
Here is the sample how you can do that.
protected void Page_Load(object sender, EventArgs e) { System.Web.UI.HtmlControls.HtmlGenericControl si = new System.Web.UI.HtmlControls.HtmlGenericControl(); si.TagName ="script"; si.Attributes.Add("type",@"text\javascript"); si.InnerText = @"alert('I am in Head Element.')"; this.Page.Header.Controls.Add(si); }
2) Add .js file reference inside page header
protected void Page_Load(object sender, EventArgs e) { System.Web.UI.HtmlControls.HtmlGenericControl si = new System.Web.UI.HtmlControls.HtmlGenericControl(); si.TagName ="script"; si.Attributes.Add("type",@"text\javascript"); si.Attributes.Add("src","util.js"); this.Page.Header.Controls.Add(si);
}
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)