RedirectResult not working with jQuery.post()
I'm trying to do an asynchronous login. When the user is authenticated I want to redirect to the user's originally requested page. The problem is that the Action Method is returning a Redirect type of ActionResult and the jQuery doesn't seem to know what to do..
I'm using the following jQuery:
$("form").s开发者_Python百科ubmit(function(event)
{
$.post($(this).attr("action"), $(this).serialize(), function(result)
{
}, "html"); // is this the right return type?
return false;
});
with this code on the server to handle the logon:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(WAPConfigUser user)
{
if (ValidateLogOn(user.UserName, user.Password))
{
string redirect = "";
if (Request.QueryString["ReturnUrl"] != null)
{
redirect = Request.QueryString["ReturnUrl"];
return Redirect(redirect);
}
else
{
return RedirectToRoute("Default");
}
}
}
Can someone suggest how I can get this to work?
Thanks
Dave
First of all, I don't think that's a good way to log a user in. Plus, what does your controller return when username or password is wrong?
Anyway, here's a way you can read the headers from the response and do the redirection with jQuery.
$("form").submit(function(event) {
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
complete: function (XMLHttpRequest, textStatus) {
if(XMLHttpRequest.status === 302) {
//if it wants to redirect
window.location = XMLHttpRequest.getResponseHeader("Location");
}
}
});
return false;
});
I didn't test this but it should give you an idea.
It turns out that I was posting to the AccountController's default route, which was returning the full page's view, which would in turn call the LogOn method. That action method would return the redirect but it was in the context of the Index View.
Somehow the redirect was 'getting lost in all the fuss', which is to say I don't know what exactly was going on, but when I started posting directly to the LogOn method it started to work.
精彩评论