Inject Javascript from ASP.NET page


There are a few ways to inject script to an ASP.NET page. Where to inject your script is depending on your need of the script on your page.

I am listing three ways to do it for one of my recent task:

1. If you want a startup type of javascript, you can use this syntax to inject the script to the end of the page just before the closing Form tag, you can use RegisterStartupScript:

 Page.ClientScript.RegisterStartupScript( Me.[GetType](), “myScript”, sbOfTheScript.ToString())

2. If you want the script goes to the top of the page just after the  Form tag, you can use RegisterClientScriptBlock:

 Page.ClientScript.RegisterClientScriptBlock( Me.[GetType](), “myScript2”, sbOfTheScript.ToString())

3. If you want the script to be injected inside the Header part of your page, you can use a HtmlGenericControl to load a literal control for the script (Assume your Head tag’s id is “Head” and with a runat=”server” mark up):

  Dim head As HtmlGenericControl = DirectCast(FindControl(“Head”), HtmlGenericControl)
            head.Controls.Add(New LiteralControl(strOfYourScriptCode))

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s