2

In ASP.NET MVC, by default, we call actions which return JsonResult in separate HTTP AJAX requests.

Is there an easy way to call actions in one HTTP AJAX request without changing too much existing code? Suppose these actions all return JsonResult.

tereško
  • 58,060
  • 25
  • 98
  • 150
Zach
  • 5,715
  • 12
  • 47
  • 62

1 Answers1

3

You can take a look at using jQuery.when, which allows to execute callback functions when all requests have completed.

$.when($.ajax("request1"), $.ajax("request2"), $.ajax("request3"))
 .done(function(data1,  data2, data3){
         // Do something with the data
 });

Or

$.when($.ajax("request1"), $.ajax("request2"), $.ajax("request3"))
.then(successCallback, errorHandler);

More example:

function showData(data1, data2) {
    alert(data1[0].max_id);
    alert(data2[0].max_id);
}

function method1() {
    return $.ajax("http://search.twitter.com/search.json", {
        data: {
            q: 'baid_harsh'
        },
        dataType: 'jsonp'
    });
}

function method2() {
    return $.ajax("http://search.twitter.com/search.json", {
        data: {
            q: 'baid_harsh'
        },
        dataType: 'jsonp'
    });
}

$.when(method1(), method2()).then(showData);​

Here's a working jsFiddle

References:

  1. SO - How can I make batches of ajax requests in jQuery?
  2. SO - jQuery.when understanding
Community
  • 1
  • 1
Harsh Baid
  • 7,199
  • 5
  • 48
  • 92
  • Your reply is very informative, thank you, Harsh. However, I think jQuery.when() still makes ajax calls in separate HTTP requests, right? Can we pack these calls into one HTTP request (for performance purpose)? – Zach Apr 17 '13 at 00:56
  • Well then you will need to write a action method say `BatchA` which calls your other actions method in once such as `Transaction1` `Transation2` and so on.. and `BatchA` may be return array of `JsonResult` and calling other action from Batch action method is like normal method invoking only.. I think this is not good approach but if you have to use it then this is the way otherwise for processing single URL against multiple action requires to override MVC Routing classes.. – Harsh Baid Apr 17 '13 at 04:38