Ray Saltrelli
Ray Saltrelli

Reputation: 4218

What happens to an ASP.NET MVC controller when the user navigates away before a response is received?

I have an AJAX action that can take a couple of minutes to complete depending upon the amount of data involved. If a user gets frustrated and navigates away while this action is still running, what happens to the controller? Does it complete anyway? Does it know the request should be abandoned and dispose of the controller object?

Upvotes: 11

Views: 2748

Answers (1)

Tommy
Tommy

Reputation: 39807

It will not cancel the request to the server as the act of navigating away does not send any information back to the server regarding that request. The client (browser), however, will stop listening for it. After the request finishes, regardless if the client was listening for it or not, the controller will dispose as it typically would.

With that said, you could get fancy and use a combination of listening for a page change on the client side and calling abort on the AJAX request to the server.

This SO question discusses how to abort a request. I could imagine setting a variable when you first start the AJAX request and then unsetting it when it finished.

Warning - Pseudo code below

var isProcessing = false;

var xhr = $.ajax({
    type: "POST",
    url: "myUrl",
    beforeSend: function(){
       isProcessing = true;
    }
    complete: function(){
       isProcessing = false;
    }
});

window.onbeforeunload = function(){
   if(isProcessing){
       xhr.abort();
   }
}

The above is very basic idea of the concept, but there should probably be some checks around if the xhr object exists, perhaps also bind/unbind the window.onbeforeunload in the beforeSend and complete object handlers for the .ajax() item.

Upvotes: 8

Related Questions