2012-03-06 127 views
0

我想在控制器中多次刷新視圖。在MVC3控制器中顯示視圖

public ActionResult MyController() 
{ 
    ViewBag.Data=CalculateSomeData(); 
    ShowView(); 
    ViewBag.Data+=CalculateMoreData(); 
    ShowView(); 
    ViewBag.Data+=CalculateExtraData(); 
    return View(); 
} 

需要很長時間來計算數據,我想以增量顯示視圖。

+0

你的行爲必須返回一個ActionResult,它發生在'return View();'行。在此之前沒有任何回報。 – veblock 2012-03-07 00:02:16

回答

0

這看起來像是一個有點ajax的工作,並且對工作的運行方式有所反思。

首先第一件事情表明你的觀點,我會把這在其自己的控制器,用戶可以請求任務

public class RequestTaskController: Controller 
{ 
    public ActionResult LongRunningAction() 
    { 
     return View(); 
    } 
} 

接下來我會創建另一個控制器做有增加的任務,並返回一個方法的工作部分結果

public class WorkController: Controller 
{ 
    [HttpPost] 
    public ActionResult CreateLongRunningTask(TaskRequestViewModel viewModel) 
    { 
     AddTask(viewModel); 
     return CurrentTasks(); 
    } 
} 


public PartialViewResult AddTask(TaskRequestViewModel viewModel) 
{ 
    // I'm using Session here because its easy 
    var currentTasks = Session["tasks"] as ConcurrentDictionary<string, Task>?? 
           new ConcurrentDictionary<string, Task>(); 

    Task task; 
    if (!currentTasks.TryGetValue(viewModel.Key, out task)) 
    { 
     task = new Task(); // what ever that is 
     currentTasks.TryAdd(key, task); 
    } 

    // do stuff with task like change progess, add payload, mark as complete 

} 



public PartialViewResult CurrentTasks() 
{ 
    ViewData.Model = Session["tasks"] as ConcurrentDictionary<string, Task>?? 
           new ConcurrentDictionary<string, Task>(); 

    // do stuff with task like change progess, add payload, mark as complete 

    return PartialView("_CurrentTasks"); 
} 

的局部視圖_CurrentTasks.cshtml將是查看/共享,並會列出什麼任務,你有什麼進步,他們也最多。

@using System.Collections.Concurrent 
@using Your.Models 
@model ConcurrentDictionary<string, Tasks> 

<ul> 
@if (Model.Count > 0) 
{ 
    foreach (var task in Model) 
    { 
     <li>@:task</li> 
    } 
} 
</ul> 

因此,這將照顧顯示它們。現在你想讓你的LongRunningAction視圖將它全部包裝起來,所以在那裏你需要做這樣的事情。

<div id="currentTasks" /> 

<script type="text/javascript"> 

var interval; 

function loadPartialView() { 
    //Populate the contents of the placeholder with the result returned by the action method 
    $('#currentTasks').load('@Url.Action("CurrentTasks", "Work")', function() { 
     // maybe do something to links 
    }); 
} 

$(function() { 

    loadPartialView(); 

    interval = setInterval(loadPartialView, 5000); 

}); 

</script> 

希望能讓你到你想要的地方。

+0

WOW。多麼驚人的答案。非常感謝你。 – Matt 2012-03-07 18:20:32

1

你不能這樣做。在視圖呈現之前,沒有任何內容被髮送到瀏覽器,並且在您從控制器返回視圖後發生。

如果您希望在計算數據時顯示頁面,則必須在兩個或多個請求中執行此操作。首先顯示沒有數據的普通頁面,然後向計算數據的服務器發出AJAX請求,並返回到腳本以顯示在頁面中。

相關問題