How to redirect to AJAX form login page (Ajax.BeginForm)?

In MVC, how can I properly handle the timeout of a page in an AJAX form. Currently, when submitting an AJAX form, the DOM of the AJAX form is replaced with the contents of the login page. I would like to redirect the whole page to the login page.

I have an ASP.Net MVC application with a partial form inside an Ajax form (AJAX.BeginForm). The application uses Windows Form Authentication. Usually, when a website expires, you will be redirected to the login page correctly. However, when the AJAX form is submitted and the website has a timeout, MVC returns the login page as the contents of the AJAX form. The controller action method is never reached. I tried jQuery.load with the same result.

controller

public ActionResult Index() { ViewData["Now"] = DateTime.Now.ToString("HH:mm:ss"); return View("Index"); } public ActionResult AjaxTimeout() { ViewData["Now"] = DateTime.Now.ToString("HH:mm:ss"); return PartialView("AjaxTimeout"); } 

Timeout.aspx

 <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %> <html> <head> <script src="/Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script> <script src="/Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script> </head> <body> Parent page: <div id="ajaxtimeout" style="height:300px; width:300px;"> <%= Html.Partial("AjaxTimeout") %> </div> </body> </html> 

AjaxTimeout.ascx

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <% using (Ajax.BeginForm("AjaxTimeout", new AjaxOptions { UpdateTargetId = "ajaxtimeout"})) { %> Return Time: <%= ViewData["Now"] %> <input type="submit" value="Submit" /> <% } %> 
+4
source share
1 answer

I do not use Microsoft scripts for our applications, since we usually use jQuery for everything, so this solution will need to be investigated for your specific case, but here is how I solve it.

Whenever I have an ajax-enabled application, I use the wrapper around the jQuery $ .ajax function to fulfill all my ajax requests. Inside the wrapper method, before it returns a response to the code that made the ajax request, it specifically checks the 401 response to see if the authentication timeout expires. If so, it simply forces the entire window to redirect to the login page.

 // The error handler for the ajax request. error: function (objXHR, status, errorThrown) { ... // Redirect to login if the ajax request returned a 401 if (objXHR.status == "401") { window.location.reload(); return; } ... } 

If you can add an error handler to the Microsoft version of ajax calls, you can probably do something like this.

+3
source

Source: https://habr.com/ru/post/1313682/


All Articles