0

Lets say we have the followings:

Login Action:

public ActionResult Login(string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;
    return View();
}

Register Action:

public ActionResult Register()
{
    return View();   
}

Login View:

<script>
    $(function () {
        var url = '@Url.Action("Login", "Account")';
        $.ajax({
            url: url,
            type: 'POST',
            data: { UserName: "user1", Password: password1 },
            success: function () {  },
            error: function () {  }
        });
    });
</script>

@{
    ViewBag.Title = "Login";
}

Register View:

@{
    ViewBag.Title = "Register"; }

<h2>Register</h2>

To process the ajax post, this is the login post action

    [HttpPost]
    public ActionResult Login(string UserName, string Password)
    {
        if (WebSecurity.Login(UserName, Password) == true)
        {
           return RedirectToAction("Register");
        else
        {
            this.ControllerContext.HttpContext.Response.StatusCode = 404;
            return new EmptyResult();
        }
    }

Now the issue and the question Okay, assuming that when the application started it goes to Account/Login, and assuming there exists account for user1, I would expect the Register View will be rendered in the browser (I am using IE 8). However, what I see, only the Login View is rendered eventhough when I trace the code in debug, the Register View is getting processed. I don't understand why I don't see the Register View?

Is my understanding wrong or is there a bug in asp.net mvc?

1 Answers1

0

What is happening is the ajax call itself is receiving the redirect and sending another request to the new Register URL. Because this is not a request from your browser, but instead the ajax, the response from the Register page is in the success response of the ajax call which your doing nothing with.

See: Returning redirect as response to XHR request

Solution

You can either use a standard form.submit instead of ajax post, or you can return a json response that includes the url to redirect to return Json( new { redirectTo = Url.Action("Register")}); and code your javascript success handler to use that redirectTo property to set window.location to cause the browser to navigate to the new URL.

Community
  • 1
  • 1
AaronLS
  • 37,329
  • 20
  • 143
  • 202