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 do the trigger but really, that isn’t important – JavaScript is just JavaScript.
You can grab the completed example at: https://github.com/rmaclean/UpdatePanelExample
Code Behind
So the first part is the code behind – I am using a static integer to just have something to update, so every time we update the text it is different. The only interesting thing to remember here that the update panel causes a partial postback so you can’t use the page load event isn’t useful 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 point, is that since we will be calling the update panel from JavaScript we need to give it an ID. In addition we can use the ClientIDMode property, which was introduced in .NET 4, to set it to static so we can easily find 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 we have the JavaScript. For this example we are using setInterval to do the call every 500ms. The code to update is just the __doPostBack function and we pass the ID of our update panel to it. That will cause the update panel to do its thing
<script> function boop(){ __doPostBack('updatePanel', ''); } $(function () { setInterval(boop, 500); }); </script>
Finally, if you are using .NET 2 or .NET 4 then you could run into a bug with the __doPostBack – thankfully this is fixed & you can read about the issue & get the fixes from Scott Hanselmans post on the issue.