這看起來像是一個有點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>
希望能讓你到你想要的地方。
你的行爲必須返回一個ActionResult,它發生在'return View();'行。在此之前沒有任何回報。 – veblock 2012-03-07 00:02:16