Thursday, 26 August 2010

Fun (!) with the ASP.NET AJAX UpdatePanel

Still unlucky enough to be developing with the ASP.NET AJAX UpdatePanel? Me too. You have my condolences. After spending some time getting to grips with it you may be at the stage where you realise that you could use it to make real time updates to areas of your web app by using a Timer to run an automatic refresh.

The problem I found initially was that doing this tended to take over the entire web app and refresh everything. I also ran into problems with Triggers - i.e. I couldn't get certain parts of the app to update because I needed to fire them through an Asycnhronous trigger and it wasn't working.

So this afternoon I set out to try and solve the problem. I am working on an app that will 'branch out' to another application on another server in certain circumstances. The user completes some actions in this second app and will then close the IE window / tab and return to my app. When this happens I want some things to change - mainly text and contents of grid views. Should be achievable with the UpdatePanel. Right?

I have set up a web form that inherits from a MasterPage. First thing on the page is the ToolKitScriptManager control, followed by an UpdatePanel called 'upMain' with UpdateMode = Conditional. I have a div with some content, and then underneath this an Accordion control with five different panes.

First thing is a note on the timer. Initially I had a set of labels in the header div (inside on UP) and a grid in the fifth pane (inside a seperate UP) that I wanted to refresh. I tried setting a Timer on each of these and using them as ASync triggers on each UpdatePanel but that didn't work - only the first Trigger would fire for some reason. I tried creating one Timer inside the Main UP and using this as the Trigger for each sub - UP but that didn't work either - it just took over the entire app and started stopping data input half way through, for example (no good for the user experience).

The answer, it turns out, is to create the Timer inside the first sub - UP and wire up the ASync triggers for both sub-UP's to this Timer. That works OK and refreshes both sets of content. To get the second sub-UP to recognise the Timer you have to give it the Unique ID that ASP.NET assigns which is something like ctl00$main$... To get this set a breakpoint on your Timer event handler and check the value of sender when it breaks - you can interrogate the object and find the UniqueID value here.

More on this later.

No comments: