0

I'm trying to redirect to another action but it's not working. The action is called but the return View() doesn't change the screen.

[HttpPost]
public ActionResult Login(LoginViewModel vm)
{
     return RedirectToAction("AlterarSenhaPadrao", new { Id = usuario.Id });
}

public ViewResult AlterarSenhaPadrao(int Id)
{
    return View(new AlterarSenhaViewModel { UsuarioId = Id });
}

Looking at the Developer Tools on Chrome, I get this:

enter image description here

So, the action is called but it doesn't return the view properly. By the way, my controller is not assigned with [Authorize]. Any ideia about why is this happening?

Thanks

UPDATE

//Shows the login page
public ActionResult Login()
{
    return View(new LoginViewModel());
}

//The submit action, the same I posted below.
[HttpPost]
public ActionResult Login(LoginViewModel vm)
{

}

And my login page: enter image description here

Deise Vicentin
  • 137
  • 1
  • 4
  • 23

2 Answers2

0

you are missing UpdateTargetId in your ajax options. Sinde your request is ajax, you tell the framework where to display your response. Try

new AjaxOptions{HttpMethod = "POST", UpdateTargetId = "mydiv"})
Robert
  • 3,353
  • 4
  • 32
  • 50
0

According to this answer and this answer you will need to pass back the url that you want to redirect to and then perform the redirect in JavaScript.

So your post action would be:

[HttpPost]
public ActionResult Login(LoginViewModel vm)
{
     return Json(new { RedirectUrl = Url.Action("AlterarSenhaPadrao", new { Id = usuario.Id }) });
}

And then your call to ajax:

@using (Ajax.BeginForm("Login", "YourControllerName", new AjaxOptions { OnSuccess = "onSuccess", ... }))
{
    ...
}

And then finally your JavaScript:

<script>
    var onSuccess = function(result) {
        if (result.url) {
            // if the server returned a JSON object containing an url 
            // property we redirect the browser to that url
            window.location.href = result.url;
        }
    }
</script>
Community
  • 1
  • 1
Dangerous
  • 4,818
  • 3
  • 33
  • 48
  • Well, so it's easyer to return a JavaScript("window.location.href = result.url;") right? – Deise Vicentin Sep 24 '15 at 17:09
  • @DeiseVicentin - I believe that with the way you are currently calling the http post action, that the MVC will return a redirect http response as you expect, but the inline JavaScript that handles the request does not know how to handle the response that is returned. That is why you have to perform the redirect yourself in JavaScript. This seems to be pretty standard practise. If you google around for "mvc ajax handle redirect" then you will find various users having the same problem and suggesting the same solution. Hope this helps. – Dangerous Sep 24 '15 at 18:40