Monday, January 17, 2011

MVC3 unobtrusive AJAX and default loading image

With MVC3's new unobtrusive AJAX and jquery.unobtrusive-ajax.js, all AJAX calls are mapped through jquery. You end up with lots of "data-ajax-xxxxxxx" attributes on your Form tag. Overall this works pretty well.

However, one issue is that _generally_ I want a 'loading' image to show on the start of each ajax call and hide at the end. In order to do that, you must provide the loadingElementId and optional loadingElementDuration to the ajax calls. Those get translated into attributes on each form call like this:

data-ajax-loading="myloadingpanel" data-ajax-loading-duration="3"


Of course I would be repeating that same information all over my code and that same information is output into each form element. You could of course create your own AjaxOptions class that provided these defaults to help with DRY. However, there are other features - what if you wanted to using one of the easing functions when showing and hiding your image? What if you wanted to center it on the screen?


JQuery has a function called ajaxSetup which sets defaults for all ajax calls. This turns out to be an easy place to attach default beforeSend and complete event that handles showing and hiding your loading image. This does not help in this scenario, because jquery.unobtrusive-ajax.js provides its own beforeSend and complete events and the default ones above will not be called.

So, I propose a new solution. Add two new entries to the ajaxSetup defaults. A showLoading and hideLoading event. You can then assign those to do whatever you want. If you do not pass in a 'loadingElementId' to the AjaxOptions then these events will be used - otherwise your will get the current behavior implemented today. (That way, this should not break any existing code). This would be something you setup and initialize in your master page/layout master.

jQuery.ajaxSetup({
   showLoading: function (XMLHttpRequest) {
    centerElement($('#loadingImage'));
    $('#loadingImage').show();
   },
   hideLoading: function (XMLHttpRequest) {
    $('#loadingImage').hide();
   }

Now you have complete flexibility in what happens when ajax calls start and stop with only one place to change it should you need to. Of course this requires a change to the jquery.unobtrusive-ajax.js code. The code addition is quite small and is shown here on lines 86 - 100. The lines with //wb are the ones I added.

Your feedback is welcomed!

No comments: