ASP.net Checking for an AJAX ScriptManager on the Current Page

Depending on the way in which you have designed your web application (Master Pages, Master Pages within Master Pages, Templates, Embedded Controls)  or if you are using a out of the box framework you may or may not know if an AJAX ScriptManager has been loaded on the current page. Lets say you have a custom control which uses the built in .Net AJAX library in order to function correctly. Instead of just assuming a ScriptManager has been placed on the page by the original page or framework developer and possibly experience exceptions caused by the lack of a ScriptManager or placing one within your control and possibly experiencing exceptions due to too many ScriptManagers on the page, you should simply check the page first. If no ScriptManager is available then add one dynamically from within your control.

A ScriptManager must be placed in the Page’s Form and there can only be one per page. The following code example checks the current page to see if a ScriptManager has been loaded, if so the control loads normally, if not a ScriptManager is instantiated and added to the current Page.Form.Controls collection and the control is then loaded.

You will also notice in this code block that I have set the AsyncPostBackTimeout to a large number. I have found on several occasions that when there are long running processes called through AJAX calls the default timeout is way too short. This timeout needs to be increased otherwise the call times out and your update panels never complete their update.

        protected void Page_Load(object sender, EventArgs e)
        {
            if (
ScriptManager.GetCurrent(this)
== null)
            {
                sManager = new ScriptManager();
                sManager.AsyncPostBackTimeout = 999999;
                Form.Controls.Add(sManager);
            }
        }

2 thoughts on “ASP.net Checking for an AJAX ScriptManager on the Current Page

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s