Search code examples
c#asp.net-mvctransactionscontrollercancellationtokensource

How to cancel on going transaction(in controller) from UI in Asp.Net MVC?


enter image description here

I am sending Transaction request from UI to controller and processing that request in controller.

This process may consume time around 10 seconds.

While processing transaction the user has a provision to cancel the transaction.

So i need to check whether cancel button has been clicked before every commit.

I Suspect when cancel button clicked I cannot pass that value as new request since new instance of controller will be created.

Another option is using static.But suggestions tell me that don't introduce static fields for controllers.

How to handle this situation? (may be with some token or still some easy work around is there ?)


Solution

  • Not sure what specific UI you are using, but what you can do is terminate the request by clicking the cancel button.

    If you are in javascript you can just call abort (content take from here)

    var xhr = $.ajax({
        type: "POST",
        url: "some",
        data: "name=John&location=Boston",
        success: function(msg){
           alert( "Data Saved: " + msg );
        }
    });
    
    //kill the request
    xhr.abort()
    

    Then in the MVC code just bind the cancellation token and check it before calling submit (or better yet use async APIs and pass in the cancellation token).

    public ActionResult Action(string param, CancellationToken token)
    {
         // do your thing
    
         if (token.IsCancellationRequested)
         {
             // abort
         }
    
         // do your thing
    }