Monday, July 25, 2011

Place Javascript inside the header tag in ASP.Net 4.0

When using DHTML, you often need to put Javascript in the header tag for setup purposes.
There is actually two different ways you can place Javascript inside the <header> tags. 


Method 1:
Dim incHeader As HtmlGenericControl = New HtmlGenericControl("script")
       incHeader.Attributes.Add("type", "text/javascript")
       incHeader.Attributes.Add("src", ResolveUrl("~\js\someJavascript.js"))
       Page.Header.Controls.Add(incHeader)


This will effectively place a .js file from the \js folder in the header section.  The ResolveURL() method simply turns the URL into a .Net Framework URL, thus allowing us to use the tilde as the base web directory.


Method 2:
Directly place the script into the header section:


Dim incHeader As HtmlGenericControl = New HtmlGenericControl("script")
       incHeader.Attributes.Add("type", "text/javascript")
       incHeader.InnerHtml = "alert('Putting Javascript in the header is freakin awesome!')"
       Page.Header.Controls.Add(incHeader)


Of course, you will need subsequent code in the body of your web form.  You can accomplish this by using a literal and populating it by your script, the RegisterClientScript  method, or the RegisterStartupScript method depending on when/where you are trying to use the script.


Happy .Netting… Saleh

No comments:

Post a Comment