Monday, February 22, 2010

Inject javascript in Head Section using asp.net

Even though it doesn't matter where the script is in the form or in the head section, you want to have it in the HEAD section of the HTML.
When you use Page.RegisterClientScriptBlock it injects the script in the body.
To inject in the HEAD section do the following...
HtmlGenericControl myScriptCode = new HtmlGenericControl("script");
myScriptCode.Attributes.Add("type", "text/javascript");
myScriptCode.InnerHtml = "alert('Alert generated by Script in Head Section of HTML');";
this.Page.Header.Controls.Add(myScriptCode); 
that should do it.check it by clicking view source and you should see the Script in HEAD section If you want to refer to a js file as a external file use the SRC attribute
string jssrc="../abc.js";
HtmlGenericControl myScriptCode = new HtmlGenericControl("script");
myScriptCode.Attributes.Add("type", "text/javascript");
myScriptCode.Attributes.Add("src",jssrc);
this.Page.Header.Controls.Add(myScriptCode);