MVC JsonResult更新进度

时间:2013-04-05 10:10:19

标签: c# jquery asp.net-mvc

MVC 4 Webapp,JQuery

我想展示一个长度程序的进展。

从JSON调用以下内容需要几秒钟......

基本上,我想做的是:

[HttpPost]
public JsonResult Update(var x)
{
    return Json(new { Result = "Working", Message = "Waiting on Server" });
    var y = contactAnotherServer(x);
    return Json(new { Result = "Working", Message = "Crunching Data" });
    var finished = doSomethingWithData(y);
    return Json(new { Result = "OK", Message = "Done" });
} 

显然这将在第一个return语句中终止。

如何做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:0)

要像这样“滚动你自己”,你需要三个独立的JsonResult方法和一个相当复杂的javascript函数。即:

控制器

public JsonResult Step1()
{
    return Json(new { Result = "Working", Message = "Waiting on Server" });
}
public JsonResult Step2()
{
    return Json(new { Result = "Working", Message = "Crunching data" });
}
public JsonResult Step3()
{
    return Json(new { Result = "Ok", Message = "Done" });
}

JS

// urls
var urls = ["/step1","/step2","/step3"];

// counter
var counter = 0;

// recursive method
var fetchAndUpdateRecursive(url){

   // get data
   $.ajax(url, {
        async: false,
        success: function(r){

              // use r to update something visually
              // then...

              // change the url
              counter++;
              url = urls[counter];

              // go again
              fetchAndUpdateRecursive(url);
        };
   });
};

// go
var urlToStartWith = urls[counter];
fetchAndUpdateRecursive(urlToStartWith);