views:

240

answers:

2

Hi Guys

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").submit(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

A: 

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.

çağdaş
It actually works for the Can you suggest a better way for me to go about this? What's wrong with the way I was doing it?
DaveDev
@Dave, There's really no need to use AJAX if you are going to be redirecting the user at the end.
çağdaş
@çağdaş, not necessarily, but I don't want to do a page refresh if the user is not successfully logging in. If it's a bad login attempt, I just want to return an error message asynchronously
DaveDev
A: 

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.

DaveDev