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()





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

4 comments:

Sandun Perera 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.

Unknown said...

Can I use JavaScript function using this way????