Daniel Peñalba Daniel Peñalba - 3 months ago 6
Ajax Question

Redirect on success and show error on failure

I have implemented a controller to create new users. When it creates the user successfully it redirects to

Index()
.

What I want is to get redirected when all is OK, but stay in the current page and see the error when something failed.

I'm using
jQuery ajax
with
MVC
.

My controller looks like this:

[Authorize]
public ActionResult CreateUser(string username)
{
try
{
//here the logic to create the user
}
catch (Exception ex)
{
string error = string.Format("Error creating user: {0}", ex.Message);
Response.StatusCode = 500;
Response.Write(error);
}
return RedirectToAction("Index");
}


The form submit is intercepted with jQuery, and then the call is made with ajax:

$("#new-user-form").submit(function() {
var form = $(this);
$.ajax({
type: "GET",
url: form.attr('action'),
data: form.serialize(),
success: function(data, textStatus, xhr) {
//At this point I would like to redirect
},
error: function(xhr, textStatus, errorThrown) {
$(".error-summary").html(xhr.responseText);
}
});

//cancel the event
return false;
});


It works fine when an error occurs, but I don't know how to implement the success case.

I'm opened to other alternatives.

Answer

If you are going to redirect in the success action why are you using AJAX? The purpose of AJAX is to refresh only parts of a site without reloading the whole page. If in the success action you are going to redirect that totally defeats all the purpose and benefits you get from AJAX. But because you asked here's what you could do:

[Authorize]
public ActionResult CreateUser(string username)
{
    ...
    if (Request.IsAjaxRequest())
    {
        return Json(new { redirectToUrl = Url.Action("Index") });
    }
    return RedirectToAction("Index");
}

And then:

success: function(data, textStatus, xhr) {
    window.location.href = data.redirectToUrl;
},