2016-06-15 82 views
0

我有設置一個消息ViewBag並返回到主頁,就像一個操作方法,幾秒鐘顯示ViewBag消息然後重定向到另一個動作

ViewBag.errormsg = "Some Temporary message"; 
return RedirectToAction("Index", "Dashboard"); 

按照這種方法,用戶將無法在該頁面中查看ViewBag.errormsg,因爲它立即重定向到儀表板,但是我希望在重定向到儀表板後顯示該消息1到2秒。

我一直在使用Task.WaitAll();方法延遲呼籲RedirectToAction喜歡這裏試過,

ViewBag.errormsg = "Some Temporary message"; 
Task.WaitAll(Task.Delay(2000)); 
return RedirectToAction("Index", "Dashboard"); 

但是它是相當愚蠢的工作,即ViewBag不會顯示消息,直到返回方法被調用時,是否有任何簡單的方法來完成這一點?

我認爲TempData是不適合我的情況,因爲我不想顯示該ViewBag消息到HomePage,它應顯示在當前頁面。

+1

留在同一頁面上的唯一方法是使用ajax。 (沒有必要將任何東西放入'ViewBag'中,然後重定向 - 立即丟失) –

+0

@StephenMuecke在Ajax和Jquery的幫助下,我可以重定向(立即或延遲一段時間)到另一個頁面嗎? – Nis

+0

你可以做一個ajax調用,得到一個響應來更新現有頁面,並使用一個javascirpt定時器在2秒後重定向,但是爲什麼?你想達到什麼目的? –

回答

0

你不能在服務器端做到這一點,你將不得不使用JavaScript。

您可以使用:

window.setTimeout(function(){ 
window.location.href='your URL'; 
}, 2000); 
0

我想通了,你想要的過程中做:

Controller => Current view => Redirect => Dashboard view

首先,包括在當前視圖您的留言:

ViewBag.errormsg = "Some Temporary message"; 
return View("CurrentView"); 

設置一個HTML元素來顯示該消息並使用JS超時o n個電流CSHTML視圖:

<script type="text/javascript"> 
function onMessageShow() { 
    var msg = "@ViewBag.errormsg"; 
    // if the message exists, set redirection to dashboard page 
    if (msg != null || typeof msg !== "undefined") { 
     setTimeout('redirect', 5000); // 5 seconds for example 
    } 
} 

function redirect() { 
    window.location.href = "@Url.Content("Index", "Dashboard")"; 
    // or use window.location.replace, depending what your need 
} 
</script> 

<html> 
<body onload="onMessageShow()"> 
    <!-- simplified for brevity --> 
    <p>@ViewBag.errormsg</p> 
    <!-- simplified for brevity --> 
</body> 
</html> 

Task.WaitAllTask.Delay在服務器端一起使用,以延遲的服務器端處理(包括async過程)的執行,在你的情況下,存在其重定向到索引頁之後的客戶端事件信息出現。

CMIIW。

相關問題