简体   繁体   中英

Show ViewBag message for some seconds then redirect to another action

I have an Action Method that sets a message to ViewBag and returns to the HomePage, like,

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

As per this approach User won't be able to see the ViewBag.errormsg in that page, Because it redirects to Dashboard immediately, But I want to show That message for 1 to 2 second then after redirect to dashboard.

I have tried using Task.WaitAll(); method to delay the call for RedirectToAction like here,

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

But it's fairly a silly work, that ViewBag won't show message until the return method is called, Is there any simple way to accomplish this ?

I think TempData is not suitable in my case because I don't want to show that ViewBag Message to HomePage, It should be shown in the current page.

You wont be able to do that on the server side, you'll have to use javascript.

You can use:

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

I figured out what process that you want to do:

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

First, include your message in current view:

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

Set an HTML element to show that message and use JS timeout on current CSHTML view:

<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.WaitAll with Task.Delay used together in server-side to delay execution of server-side process (including async processes), in your case there are client-side events which redirecting to index page after message appears.

CMIIW.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM