DevDotNet
DevDotNet

Reputation: 163

Call a function in controller after returning response from ActionMethod

I am doing an Ajax call which calls an action method as follows-

The action method returns response after doing some piece of work.
I want to call another method once this response is submitted back to the Ajax call.

 $.ajax({
        url: "/Test/TestActionMethod"; ,
        data: somejsondata,
        dataType: "json",
        type: 'POST',
        async: true,
        contentType: 'application/json; charset=utf-8',
        success: function (response) {

        }
});

And this is my actionMethod

public JsonResult TestActionMethod(bool test1, bool test2)
{  
      object response = null;
      // some code

      return Json(response, JsonRequestBehavior.AllowGet);

      Save(); // Here I want to call this method
}

I know I can't call Save() method like this I also know that we can make another ajax call to call this save method however, I am looking for the way by which this save method can be called in controller itself instead of making another Ajax call.

Is there any way to do this?

[P.S. I don't want to call this before response is submitted as this function takes time and hence response time also increases]

Upvotes: 3

Views: 2901

Answers (2)

Askar Rayapov
Askar Rayapov

Reputation: 168

Just fire and forget using Task.Run() before returning.

public async Task<IActionResult> ActionName()
{
    Task.Run(() => Save());
    return Ok();
}

private void Save()
{
    Thread.Sleep(5000);
}

Upvotes: 3

Chetan
Chetan

Reputation: 6901

You can not execute the code after returning from the Controller Action method.

You can use background worker to trigger the time taking function asynchronously.

//Save method which will be taking time.
private void Save(CancellationToken ct)
{
    if (ct.IsCancellationRequested)
            return;

    // Long running code of saving data.. 
}


public JsonResult TestActionMethod(bool test1, bool test2)
{  
    object response = null;
    // some code

    // Initiating background work item to execute Save method.
    HostingEnvironment.QueueBackgroundWorkItem(ct => Save(ct));

    return Json(response, JsonRequestBehavior.AllowGet);
}

Upvotes: 0

Related Questions