Ajax Redirect to page instead of refreshing target

I use a partial view to log in and would like to redirect the user to a new page with success and show validation errors in a partial view if the model is invalid. The goal of ajax is updated, and success or failure. If the model is valid, it displays the whole new page in the refresh task, but I want it to be redirected to the new page. I tried Redirect and RedirecttoAction, but it did not get the desired results. Any ideas on what I can do get an ajax update to redirect to a new page, not a goal update. Also, let me know if I use the wrong approach.

Partial View Code:

<% using (Ajax.BeginForm( "LogOn", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "SignInForm" }, new { id = "SignInForm", ReturnUrl = Request.QueryString["ReturnUrl"] })) { %> <<Page HTML Controls>> <input type="submit" value="Log On" /> <% } %> 

Here is the relevant controller code:

  public ActionResult Logon(LogOnModel model,string returnUrl) { if (ModelState.IsValid) { //Login Logic Code if (!String.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "App"); } } // If we got this far, something failed, redisplay form if (Request.IsAjaxRequest()) return PartialView("LogOnControl"); return View(model); } 
+6
asp.net-mvc asp.net-ajax asp.net-mvc-partialview
source share
1 answer

To do the redirection, you need to do this on the client side. That way you can no longer use UpdateTargetId , but you should use the OnSuccess option OnSuccess . You will also need to change the action of the Logon controller so that in case of a redirect, you test if you are an ajax request and in this case return a Json object with the redirect URL that will be used in javascript:

 if (ModelState.IsValid) { if (string.IsNullOrEmpty(returnUrl)) { returnUrl = Url.Action("Index", "App"); } if (Request.IsAjaxRequest()) { return Json(new { returnUrl = returnUrl }); } return Redirect(returnUrl); } 

And in the view:

 <% using (Ajax.BeginForm( "LogOn", null, new AjaxOptions { HttpMethod = "POST", OnSuccess = "success" }, new { id = "SignInForm", ReturnUrl = Request.QueryString["ReturnUrl"] })) { %> <<Page HTML Controls>> <input type="submit" value="Log On" /> <% } %> <script type="text/javascript"> function success(context) { var returnUrl = context.get_data().returnUrl; if (returnUrl) { window.location.href = returnUrl; } else { // TODO: update the target form element with the returned partial html } } </script> 
+8
source share

All Articles