11

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!

brothers28
  • 1,196
  • 17
  • 23
  • Use JavaScript window.location.href. http://stackoverflow.com/questions/7276677/jquery-redirect-to-url-after-specified-time – Tarek Saied Jul 11 '14 at 14:39

4 Answers4

15

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);
ryudice
  • 36,476
  • 32
  • 115
  • 163
7

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/">
    }
}
Michael Cook
  • 1,676
  • 2
  • 26
  • 47
2

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")';
}
Ross Bush
  • 14,648
  • 2
  • 32
  • 55
1

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.

David
  • 208,112
  • 36
  • 198
  • 279