MVC redirect to another page after a four second p

2020-07-09 03:00发布

问题:

I'm relatively new to MVC, but I have a problem:

Currently, when a user signs into our site for the first time, they are redirected to a change password page; they must change their password before they can access any of the main functionality of the site. After they change their password successfully though, I want to show my custom "Password successfully changed" message on the change password page; I currently do this. After I display my custom message on my change password page, I want to wait a few seconds and then redirect them to the home page.

I want to be able to do something like this:

//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");

Thanks!

回答1:

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';
}, 4000);


回答2:

Another method you could consider is an old school meta-refresh

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

Which you could control with a property on your model or a value in the ViewBag

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

Since this needs to be in the header, you might need to put a header "section" in your _layout

<head>
    ...
    @RenderSection("header", required: false)
</head>

Which you can then use in your view like

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


回答3:

You will have to do this on the client as your server processing ends at return View(); for the request. You have a few options on the client, for example, use a javacript timer and after so many miliseconds invoke your next action.

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


回答4:

The "wait 4 seconds" part happens client-side, so the resulting redirect should also be client-side. You can redirect in JavaScript after 4 seconds with something like this:

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

Note the use of the Url.Action() helper method to inject the resulting URL into the JavaScript code.