2010-08-26

Making sure JavaScript gets called after an AJAX Partial Postback in ASP.NET

ScriptManager.RegisterStartupScript(Page page, Type type, string key, string script, bool addScriptTags)

Notice the first parameter of this method, as it has an overload that takes a Control as its first parameter.  When you use the Control overload, it only registers the startup script once on the initial rendering of the page.

If you use the Page overload listed above, it will register it for every asynchronous postback to ensure your JavaScript is executed everytime.

Remember to use ScriptManager and not ClientScriptManager...

From the Remarks on the MSDN article for the overload listed above:
"You use this method to register a startup script block that is included every time that an asynchronous postback occurs. To register a script block for a control that is inside an UpdatePanel control so that the script block is registered only when the UpdatePanel control is updated, use the RegisterStartupScript(Control, Type, String, String, Boolean) overload of this method.

If you want to register a startup script that does not pertain to partial-page updates, and if you want to register the script only one time during initial page rendering, use the RegisterStartupScript method of the ClientScriptManager class. You can get a reference to the ClientScriptManager object from the ClientScript property of the page."

Also very important:
Make sure you have the following using statement in your codebehind...
using System.Web.UI;

If you don't, you will get the error:
Cannot access internal property 'ScriptManager' here