Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Clean ASP.NET page initialization

0.00/5 (No votes)
11 Jul 2011 1  
Initialize Master Page, Page, and Controls in a single JavaScript call.

Here is a clean way to initialize all the JavaScript in your ASP.NET page. It is accomplished using a custom initializer class. This example uses jQuery.


In the master page itself or in a .js class referenced in your master page, declare your class:


JavaScript
//Initializer class
function Initializer() {
    //A simple array of functions
    this.functionArray = new Array();
}

//The method to insert functions to the initialization stack
Initializer.prototype.addStep = function (func) {
    this.functionArray.push(func);
}

//The initializing method
Initializer.prototype.init = function () {
    for (x in this.functionArray) {
        this.functionArray[x]();
    }
}

The init() method loops through the function array and executes each method.


Add this block to the master page:


JavaScript
<script type='text/javascript'>
    //Create instance of the initializer
    var initializer = new Initializer();

    //JQuery's 'onready' function
    $(document).ready(function () {
        initializer.init();
    });
</script>

In your user controls and/or pages, add your initialization code:


C#
//Method called by Page_Load
private void CreateInitScript()
{
    string script = "function doSomething() {
       //Perform some actions
    }";

    ClientScriptManager cs = Page.ClientScript;

    //Insert your script into the page
    cs.RegisterClientScriptBlock(this.GetType(), "MyScript", script, true);


    //Add a call to your method to the validation stack
    string validationScript = "if(initializer){ initializer.addStep(doSomething); }";

    cs.RegisterStartupScript(this.GetType(), "initscript", validationScript, true);
}

This code is very handy when you want to handle your control's initialization at the same time as the hosting page and the master page if you use one.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here