Last Updated: February 25, 2016
· gifthlong

Execute JavaScript when an UpdatePanel is updated

I’ve just spent a few hours banging my head against a wall trying to get ASP.NET to execute a JavaScript function each time an UpdatePanel is updated. Simply putting the script within the ContentTemplate tags does not work. Instead, to get the JavaScript to execute on PostBack you need to use ScriptManager.RegisterStartupScript to register the script to be run.

protected void Page_Load(object sender, EventArgs e)

RegisterStartupScript is a static method on the ScriptManager class. You do not need to have an actual ScriptManager in scope to call this function (for example, you might be coding within a UserControl and have the ScriptManager on the Page).

The first parameter is the UpdatePanel you want to associate the script with. The second parameter is a type parameter, we’ll just use the type of the current object for this. Now we get to the interesting bits. The third parameter, “MyAction”, is a key to identify the script, allowing you to reference or update it in the future if you wish. Next we have the script itself. This can be a block of inline JavaScript but I prefer to wrap everything I want to happen in a function and call that instead. The final parameter is a flag to indicate whether the ScriptManager should wrap your code in script tags. You can do this manually if you want, but I prefer to set this flag to true and let somebody else worry about it.

ASP.NET will output the following code at the bottom of your page and execute it on PostBack. Provided you have defined the function doMyAction() somewhere everything should work as you expect.