Contact Us

Execute JavaScript when an UpdatePanel is updated


June 4, 2010 | by Adam Pope

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.

Let’s look at the code we need:

protected void Page_Load(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(
                        upPanel,
                        this.GetType(),
                        "MyAction",
                        "doMyAction();",
                        true);
}

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.

<script type="text/javascript">
    doMyAction();
</script>

If you set the final parameter to false you would get the following:

    doMyAction();

You can pass variables from your C# code to your JavaScript by including them in your function call:

protected void Page_Load(object sender, EventArgs e)
{
    int myVar = 5;
    ScriptManager.RegisterStartupScript(
                        upPanel,
                        this.GetType(),
                        "MyAction",
                        "doMyAction(" + myVar + ");",
                        true);
}

We’d then get the following output:

<script type="text/javascript">
    doMyAction(5);
</script>