February 13, 2011

Register Script into Page Header from ASP.NET Content Page




In a previous article, I had explained how to Call a JavaScript function from ASP.NET Content Page.

We used the ‘RegisterClientScriptInclude’ to register script from a Content Page. However this approach adds the JavaScript reference inside the <body> tag of the page and not the <head>. A reader Simone mailed me asking if it was possible to use the same method to register the script into <head> portion of the page.

The answer is using the ‘RegisterClientScriptInclude’, I think it is not possible natively to add script to the <head> element. However there is an alternate method using the System.Web.UI.HtmlControls.HtmlGenericControl class as shown below:

protected void Page_Load(object sender, EventArgs e)
{
HtmlGenericControl ctrl = new HtmlGenericControl("script");
ctrl.Attributes.Add("type", "text/javascript");
ctrl.Attributes.Add("src", @"Scripts\Alert.js");
this.Page.Header.Controls.Add(ctrl);
}

Run the application, right click the page and View Source.

As you can see, the script is now registered in the <head> instead of the <body>.



Giving me +1 tells me you liked this article! Thanks in advance




About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Register Script into Page Header from ASP.NET Content Page"
  1. Abhishek Sur said...
    February 13, 2011 at 8:57 AM

    But we can also use ContentPlaceHolder in Head of masterpage.

    Any special advantage we could get from dynamically producing script block ? For me Html design is easier to handle

    :)

  2. Suprotim Agarwal said...
    February 14, 2011 at 3:43 AM

    Abhishek: The advantage is in cases when your client script depends on information that is not available until run time

 

Copyright © 2009-2013 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions