Updating a View Using Async Operation in MVC

I am writing a small internal web application. I need to do a very long operation (which can take about an hour) by pressing a button and tell the user as soon as the operation is completed with its result.

In other words, I need a button to start the async operation and update the view with the results after completion (about an hour later).

Edit: The operation may use some kind of update mechanism in the view. The result can be sent to the view after a little delay (no need to update in real time)

+7
c # model-view-controller asp.net-mvc async-await
source share
4 answers

You can use SignalR, but for this it can be a little overpriced. Another option is to configure another controller action that checks if the task is completed. Then, on the client side, you can use jQuery to create ajax requests for this controller action. When the action returns fully, you can show a warning or otherwise refresh the page.

$.ajax({ type: 'GET', url: http://mysite.info/tasks/checkComplete/5, success: function (response) { if (response == 'true') { alert('Task complete'); } } }); 

Regarding server side events, I don't think this is the case when I will use async / wait. If your task really works for an hour, I got the feeling that you will run into timeout problems, etc. I will have a controller action that is used to run the task, but all it does is put a request to run in the database. Then I will have an external β€œworker” that checks the queries in this database and performs the tasks. When the task is completed, it will update this database record to mark it completed. Then the action of the CheckComplete controller from my example above will check the database to see if the task is really completed.

+3
source share

As stated in the comments, I recommend you take a look at SignalR , it is not so difficult to implement.
You will need to implement the server on your website, send a message to the server at the end of your lengthy operation, and update the view when the message is received.
Microsoft's tutorials should be clear enough for this.

0
source share

The low-tech solution from the age side before AJAX and WebSockets was to simply write data back in response (usually a progress report).

So instead of doing asynchronous work, you call something like

 Response.Write("<script>reportProgress(" + progress + ");</script>"); Response.Flush(); 

occasionally. This has its problems, but it can be a good way if you need to support weird platforms or very old browsers.

0
source share

Ummm,

I will try to create a flag on the server when finished. In MVC, you can create a TIMER obj that checks, for example, every minute if the server shuts down, and start this timer in a new thread that does not block the application.

(sorry for my English).

-one
source share

All Articles