MVC在暂停四秒后重定向到另一个页面

MVC redirect to another page after a four second pause

本文关键字:重定向 另一个 四秒 暂停 MVC      更新时间:2023-09-26

我对MVC比较陌生,但我有一个问题:

目前,当用户第一次登录我们的网站时,他们会被重定向到更改密码页面;他们必须更改密码才能访问网站的任何主要功能。在他们成功更改密码后,我想在更改密码页面上显示我的自定义"密码成功更改"消息;我现在就是这么做的。在我的更改密码页面上显示自定义消息后,我想等待几秒钟,然后将它们重定向到主页。

我希望能够做这样的事情:

//User successfully changes password on ChangePassword page
return View(); //This keeps them on the ChangePassword page and shows the success message
//Wait five seconds on ChangePassword page
//Redirecttoaction("Index", "Home");

谢谢!

你不能在服务器端这样做,你必须使用javascript。你可以使用

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

您可以考虑的另一种方法是老式的元刷新

<meta http-equiv="refresh" content="4; url=http://example.com/">

你可以用模型上的属性或ViewBag

中的值来控制它
@if(Model.DoRedirect) {
    <meta http-equiv="refresh" content="4; url=http://example.com/">
}

因为这需要在标题中,你可能需要在你的_layout

中放一个标题"section"
<head>
    ...
    @RenderSection("header", required: false)
</head>

你可以在你的视图中使用,比如

@section header
    @if(Model.DoRedirect) {
        <meta http-equiv="refresh" content="4; url=http://example.com/">
    }
}

您必须在客户端上执行此操作,因为您的服务器处理结束于return View();对于请求。您在客户端上有几个选项,例如,使用javascript计时器,并在这么多毫秒后调用下一个操作。

function onTimerElapsed(){
    window.location='@Url.Action("SomeAction","SomeController")';
}

"等待4秒"部分发生在客户端,因此结果重定向也应该是客户端。在JavaScript中,你可以在4秒后重定向,像这样:

setTimeout(function () {
    window.location.replace('@Url.Action("Index", "Home"')
}, 4000);

注意使用Url.Action() helper方法将结果URL注入JavaScript代码。