Updating an update panel from JavaScript
At TechDays in Cape Town, I was asked an interesting question: how do you force an Update Panel to update from JavaScript? The asker was using SignalR to trigger it, but really, that isn’t important—JavaScript is just JavaScript.
You can grab the completed example at: https://github.com/rmaclean/UpdatePanelExample
Code Behind
The first part is the code behind—I’m using a static integer to update a value, so every time we refresh the text, it changes. The only interesting thing to remember is that the Update Panel causes a partial postback, so you can’t rely on the Page_Load event here. In the example, I used the Update Panel’s OnLoad event to update the text.
public partial class _default : System.Web.UI.Page
{
string thingyText = "loaded";
static int counter = 0;
protected void updatePanel_Load(object sender, EventArgs e)
{
counter++;
thing.Text = thingyText + counter.ToString();
}
}
Update Panel Config
A minor detail: since we’ll be calling the Update Panel from JavaScript, we need to give it an ID. Additionally, we can use the ClientIDMode property, introduced in .NET 4, to set it to Static so we can easily reference it in JavaScript.
<asp:UpdatePanel ID="updatePanel" OnLoad="updatePanel_Load" ClientIDMode="Static" runat="server">
<ContentTemplate>
<asp:Label Text="nothing" ID="thing" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
JavaScript
Finally, here’s the JavaScript. For this example, we’re using setInterval to trigger the call every 500ms. The code to update is just the __doPostBack function, passing the Update Panel’s ID. That causes the panel to refresh!
😊
<script>
function boop() {
__doPostBack('updatePanel', '');
}
$(function () {
setInterval(boop, 500);
});
</script>
Note: If you’re using .NET 2 or .NET 4, you might encounter a bug with __doPostBack—fortunately, this is fixed. You can read about the issue and get fixes from Scott Hanselman’s post.