Sunday, 4 March 2012

How to add startup JavaScript code from Content Page to Master Page


 If you are creating a website that has Master and Content Pages and if you need to add some JavaScript code from your Content pages that should run when the page is loaded you fill find out that its not straightforward.
Content page do not have all the elements of HTML page like BODY tag that you could hook up to and add your script code to its onload event.

Luckily the designers of ASP.NET thought about this so there is a method RegisterStartupScript.
You can use it to add JavaScript code programmatically to your ASP.NET pages and also from Content Pages and that code will be executed when the page is loaded.

Here is how to use it, add this code to your Content Page code behind - PageLoad event:
    protected void Page_Load(object sender, EventArgs e)
    {
        Type type = GetType();
        const string scriptName = "alertPopup";

        if (!ClientScript.IsStartupScriptRegistered(type,scriptName))
        {
            ClientScript.RegisterStartupScript(type, scriptName, "alert('Hello from content page!')", true);
        }

    }
 
The code is self-explanatory: we retrieve the Type of the current page instance and we give a unique name to our script block.
We check if there is already registered script with this name using IsStartupScriptRegistered method (each script block must have a unique name) and if its not we register it.
The last parameter addScriptTags is set to True and it tells the method to enclose our code with JavaScript tags so we don't have to do it.

The Result:
The code will display a PopUp alert with our message when the page is loaded.

NOTE:
JavaScript code registered like this will be executed immediately after the page finishes loading but before Master Page's PageLoad event is fired as stated in the RegisterStartupScript MSDN Documentation.
Also if you register more than one script in this way, there is no guarantee in which order they will be executed, so if you need to control their order of execution, you can merge them all into one script in proper order and register them as one script.
Post a Comment