Executing JavaScript after a Partial Render

I had a fun day debugging some ASP.NET plus jQuery this week, and came across something I’ve known is possible for some time, but that I’ve never actually needed to do... and that was to ensure a bit of JavaScript ran once an UpdatePanel had refreshed as part of a partial render.

It turns out that this is easy; all you need to do is register your JavaScript code block with some methods on ScriptManager, rather than using the standard ClientScript methods.

For example, consider the HTML below (I’ve omitted the rest of the page including the script manager, but it is in the download);

<asp:Button

ID="ClickMeButton"

runat="server"

Text="Click Me to Refresh Below"

onclick="ClickMeButton_Click" />

<div style="background: black; color: White">

<asp:UpdatePanel

ID="MyUpdatePanel"

runat="server"

UpdateMode="Conditional">

<Triggers>

<asp:AsyncPostBackTrigger

ControlID="ClickMeButton"

EventName="Click" />

</Triggers>

    <ContentTemplate>

        Last Updated:

<asp:Label

ID="UpdateTimeLabel"

runat="server" />

</ContentTemplate>

</asp:UpdatePanel>

</div>

<div id="log">

</div>

Here we have a simple UpdatePanel, with a button that triggers the async postback. There is also an empty DIV with ID “log”.

In the server-side code of the button click event I have some code that looks a bit like this;

string time = DateTime.Now.ToLongTimeString();

ScriptManager.RegisterStartupScript(

UpdateTimeLabel,

typeof(Label),

"UpdateTimeLabelStartupScript",

CreateScript(time),

true);

The CreateScript function simply returns some JavaScript in a string that reads as follows (the {0} is replace with a time);

$('#log').append('Last Server Run: {0}<br />');

This uses jQuery to append a message to our “log” DIV.

There is also an alternative though; using the Sys.Application.add_load method to attach a page load script function, or creating a pageLoad JavaScript function that is a synonym for the same thing. I’ve done the latter;

function pageLoad() {

    $('#log').append('pageLoad executed<br />');

}

This function is executed when the page initially renders and when every partial render completes. This means the content of my “log” DIV rapidly starts to look like this;

pageLoad executed

Last Run: 21:56:12

pageLoad executed

Last Run: 21:56:14

pageLoad executed

Last Run: 21:56:19

pageLoad executed

Easy huh?

I hope that adds some clarity to your options for executing script as the result of a partial postback. Check out the attached if you want to try it yourself.

PartialRenderPlusScript.zip