Question

So I have a very long function in C#. My form contains a partial view that displays a string. simple. Once the form is submitted, the controller fires the long function. What I try to do is display in that partial view a text explaining how the process is going. But I don't know how to make that ajax call to refresh without stopping my function. Here is what I have:

Partial:

@model System.String
    Performing: @Model.ToString()

Main View:

<div  id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px;
    top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001;
    opacity: .8; filter: alpha(opacity=70);display:none">
    <p style="position: absolute; top: 30%; left: 45%; color: White;">
        Saving, please wait... <img src="../../Content/images/ajax-loading.gif">
    </p>
    <p style="position: absolute; top: 37%; left: 45%; color: White;">
        @Html.Partial("_ProgressList", completedProgress);
    </p>
</div>

Controller:

[HttpPost]
[ValidateInput(false)]
public ActionResult longFunction(FormCollection collection)
{
    PartialView("_Partial", response); //Update here but continue execution
    ...
    ...
}

Is this possible?

Was it helpful?

Solution

You should be doing something like a realtime update to the client as some function finishes executing. SignalR is a good candidate to opt for.

Here is a sample dummy program which sends updates to the client. You may replace the Thread.Sleep part with calls to your sub methods and calulate the percentage with some algorithm. This program is to give you an idea. This is not the optimal solution!

[HttpPost]
public ActionResult DoIt()
{
    var context = GlobalHost.ConnectionManager.GetHubContext<IssuesHub>();
    Thread.Sleep(3000);
    context.Clients.All.updateProgress(new { Status = "10 %" });
    Thread.Sleep(3000);
    context.Clients.All.updateProgress(new { Status = "50 %" });
    Thread.Sleep(3000);
    context.Clients.All.updateProgress(new { Status = "60 %" });

    return Json(new { Status = "100%" });
}

And in the client

$(function () {
    var progress = $("#progress");
    var chat = $.connection.issuesHub;       
    chat.client.updateProgress = function (result) {
        progress.html(result.Status);
    };                
    $.connection.hub.start();

  $("#someSubmitButton").click(function(e){
    e.preventDefault();
    $.post("@Url.Action("DoIt","Home")");
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top