Novice101
Novice101

Reputation: 3

Making async call to Controller function (void). Not getting control back to UI

I am working on a MVC 5 based report generating web application (Excel files). On one "GenerateReports" page, on button click, I am calling StartMonthly function. This takes control to a void method "GenerateReportMainMonthly" in the controller. This method calls another void method "GenerateReportMain". In GenerateReportMain, there are 5 other void functions that are being called.

I do not want the control to get stuck at back-end until the report generation is completed. On button click, an alert box should show "Report Generation started." and the control should come back to the "GenerateReports" page.

I have tried ajax but have not been able to get the control back to UI. How can I get the control back to the same page without waiting for the back-end process to complete?

$('#btnStart').on('click', StartMonthly);
function StartMonthly() {
        var url = '/GenerateReport/GenerateReportMainMonthly';
        window.location.href = url;
    }
public void GenerateReportMainMonthly()
        {
            _isDaily = false;
            GenerateReportMain();
        }

Upvotes: 0

Views: 40

Answers (1)

timur
timur

Reputation: 14577

It seems you are after running background tasks in your controllers. This is generally a bad idea (see this SO answer) as you might find that your server process has been killed mid-way and your client will have to handle it somehow.

If you absolutely must run long-ish processes in your controller and cannot extract it into a background worker of some sort, you can opt for something like this SO answer suggests. Implementation will vary depending on your setup and how fancy you are willing/able to go, but the basics will ramain the same:

  1. you make an instantaneous call to initiate your long action and return back a job id to refer back to
  2. your backend will process the task and update the status accordingly
  3. your client will periodically check for status and do your desired behaviour when the job is reported complete.

If I were to tackle this problem I'd try to avoid periodic polling and rather opt for SignalR updates as describled in this blog post (this is not mine, I just googled it up for example).

Upvotes: 1

Related Questions