I was recently tasked with upgrading an existing DotNetNuke module to use jQuery for some client side functionality. The module itself was nothing special; a simple search control that returned results which could be paged through and also filtered using dropdowns at the top. Naturally it was using the typical ASP.NET postback model to refresh its data.
I started with the client side work and soon had the desired jQuery async service calls updating my UI nicely. The smoothness of jQuery really made the ugliness of the postbacks stand out, so I decided to enable partial rendering of the module in DotNetNuke. I know using UpdatePanels is considered a bad thing (see related post at Encosia for an explanation), but in this case I had tight timelines, and the improved function I felt justified the means. With a few clicks the ugly postbacks were gone and the module itself was operating much more smoothly. Until I started doing some testing that is.
When the module first loaded the first page of search results were displayed, and the jQuery popovers with service calls were working fine. But if I did anything to cause the module to postback, jQuery no longer worked. It was really puzzling. I did some research to learn more about how jQuery worked, and in particular how it works with AJAX UpdatePanels.
In a typical request:
- Page Loads
- jQuery attaches events, hides items etc
- Async Request Happens
- UpdatePanel handles the request
- Async Request Finishes essentially rebuilding the elements
jQuery has not had a chance to attach the events etc for the new items because of the async rebuild. When AJAX finishes processing the page the $(document).ready() function is not called and jQuery isn’t wired up.
I found several potential solutions which all basically centered on a common theme – by invoking an event to happen once the Ajax UpdatePanel finishes loading. The usual way this was done was by attaching this event to the Sys.Application. To do it this way, add the following script inside your update panel at the bottom of the update panel, being the last thing in the update panel to load:
While this might be a fine solution for a regular ASP.NET application, it isn’t really workable within a DotNetNuke module. The biggest issue being that if you enable partial rendering you really don’t have access to the UpdatePanel as DNN adds it for you automagically. That problem aside, it just seems overly complicated. Luckily there is an easier way.
We need to find a way to initialize jQuery again after the AJAX is done processing. The answer lies within the AJAX Life-Cycle Events. As it turns out, any method titled pageLoad found within the scripts on a page will get hooked up to the Sys.Application.load event. A simpler approach would be to use something like the following: