Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 531
DevDotNet Avatar asked Aug 28 '26 00:08

DevDotNet


1 Answers

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);
}
like image 165
Askar Rayapov Avatar answered Aug 29 '26 14:08

Askar Rayapov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!