Question

In my controller I need to make some operations that may require a long time, so I'd like to update the view at the end of each step. I am a beginner in MVC, and according to what I know every time I want to update the view from the controller I have to do something like

ViewBag.Result = "OK";
return View();

but in this case the control goes to the view, and the controller can't continue its operations.

Thanks for any help!

Was it helpful?

Solution 3

I would use separate thread to run long running operation on the server, and I would make Ajax requests to the server to get operation status each N seconds.

You also can think about WebSockets/SignalR. But not all the browsers supports this technology. There is some libs on NuGet for SignalR implementation. http://nuget.org/packages?q=signalr

I recommend you to check this video http://www.asp.net/signalr/videos/getting-started/signalr-and-web-sockets

If you need faster solution, you can update view like that:

<p>@Model.OperationState</p>

@if (Model.OperationIsInProgress){
<script>
   setTimeout("location.reload(true);", 10000);
<script>
}

but it is not async approach. This js reloads page every 10 seconds.

To start new thread you can use simple System.Threading classes:

using System.Threading;

var thread = new Thread(() => {
    //Call your long running operation here
});
thread.Start();

OTHER TIPS

You have to start the long running operation in a separate Thread for example by using the TPL and return a view immediately:

public ActionResult StartLongRunningAction() {
    Task.Factory.StartNew( () => {

        // code your long running action here or call a method
    });
    return View();
}

To send progress messages to your client i suggest you to use a framework like SignalR.

Simply use ajax to get operation info. jQuery can help you to simplify ajax code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top