显示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消息,应在当前页面中显示。

您将无法在服务器端执行此操作,您必须使用JavaScript。

您可以使用:

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

我想出了您想做的过程:

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

首先,将您的消息包括在当前视图中:

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

设置一个HTML元素以显示该消息并在当前CSHTML视图上使用JS超时:

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

最新更新