Call JavaScript from an ASP.NET AJAX Update Panel in Content Page Load

While calling a JavaScript function from a Content Page Load method, you can use the ClientScript.RegisterStartupScript method. However the same does not work if the content page is wrapped inside an ASP.NET AJAX Update Panel. To call a Javascript function at page load in an Update Panel scenario, you need to instead use the  ScriptManager.RegisterStartupScript method that registers a startup script block with the ScriptManager control and adds the script block to the page.

Here’s an example. In the Page_Load of the content page, write the following code:

image

This is the code that registers a script block

ScriptManager.RegisterStartupScript(this, this.GetType(), "call", str.ToString(), false);

Using the RegisterStartupScript(Page, Type, String, String, Boolean) overload registers a startup script block every time that an asynchronous postback occurs.

Update: On the same note, check out a nice article by Krishna Using .NET’s Register Script methods with jQuery’s $(document).ready()


Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) 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 is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

3 comments:

Sandun said...

It is recommended to use ToolkitScriptManager instead of ScriptManager in ASP.net 4.0 Ajax toolkit.

Suprotim Agarwal said...

Sandun: Thanks for bringing up the ToolScriptManager. One of the main reasons why you would want to use the ToolScriptManager (which by the way inherits from ScriptManager) is that it reduces the number of ScriptResource.axd calls, by combining 'relevant' scripts and reducing n/w traffic.

Depending on a request, it's smart to generate a combined script file which has only those scripts that the browser has not yet downloaded.

Javascript Countdown Timer said...

very cool & good tips, thank you very much for sharing.