Ajax.BeginForm checks if a request has been redirected

How to determine if the async request aynax form form has been redirected? In my case, the request is redirected to the login page if the user session is closed.

I tried to check the arguments of the OnComplete, OnSuccess, and OnBegin events (OnFailure is not called), but no one helped.

Currently, I have a whole login page populated in the div of the current page in case the session is closed.

The only way I can see how to avoid this is with code like this:

function onSuccessPost(a,b,c) { if (a.indexOf("<!DOCTYPE html>") == 0) { window.location = window.location; } // ... } 

But this solution seems a little ugly.

Any ideas?

+4
source share
2 answers

Do not redirect controller actions that are invoked through AJAX. You can use JSON:

 public ActionResult Foo() { var url = Url.Action("Bar", "Baz"); return Json(new { location = url }, JsonRequestBehavior.AllowGet); } 

and now in your AJAX callback:

 success: function(result) { window.location.href = result.location; } 

Obviously, if you intend to always redirect from the client side after an AJAX request, this completely destroys any benefits from AJAX. Just call the controller action using the standard link => in this case it makes no sense to use AJAX.


UPDATE:

It looks like you are trying to intercept a redirect to the LogOn page when the authentication cookie expired. Phil Haack wrote about this on his blog: http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx

In this article, it illustrates how you can prevent the Authentication Forms module from automatically redirecting you to the LogOn page, and instead send a 401 status code, which can be intercepted by your AJAX request and redirect to the client.

0
source
 public ActionResult PossibleRedirectAction(bool isRedirect = false) { ViewBag.IsRedirect = isRedirect; } 

And put this code in the action from which you redirect:

 RedirectToAction("PossibleRedirectAction", new {isRedirect = true}); 
0
source

All Articles