更新部分视图ajax,没有动作结果

时间:2014-02-03 21:50:39

标签: c# ajax asp.net-mvc razor partial-views

所以我在C#中有很长的功能。 我的表单包含一个显示字符串的局部视图。简单。 提交表单后,控制器将触发long函数。 我尝试做的是在局部视图中显示一个文本,解释过程的进展情况。 但是我不知道如何在不停止我的功能的情况下让ajax调用刷新。 这就是我所拥有的:

部分:

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

主要观点:

<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>

控制器:

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

这可能吗?

1 个答案:

答案 0 :(得分:1)

当某些功能完成执行时,您应该对客户端进行类似的实时更新。 SignalR是一个很好的选择。

这是一个示例虚拟程序,它将更新发送到客户端。您可以使用对子方法的调用替换Thread.Sleep部分,并使用某种算法来计算百分比。这个程序是给你一个想法。这不是最佳解决方案!

[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%" });
}

在客户端

$(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")");
  });
});