Redirect and Ajax Redirect in MVC
In the sample example I will have various methods to perform redirects from main page to “About” page of a simple MVC site. In my opinion, there are only 3 cases – 2 goods and one bad – to perform redirection with or without Ajax.
First case: A sample redirect and a sample link:
The action is
public ActionResult RedirectToAboutNoAjax() { return RedirectToAction("About"); }
and in the View I call in a simple <a href, generated by :
@Html.ActionLink("Redirect no ajax to about", "RedirectToAboutNoAjax", "Home")
When you click the link, the following happens : a 302 Found answer is send to the browser with the new Location. The browser goes to the page requested.
Second case( not good ajax): Call same action from ajax – in hope that ajax will do the redirect alone, without coding further.Modified only the code that calls the action, transforming to ajax.
<a href="javascript:AjaxNotGoodForRedirect('@Url.Action("RedirectToAboutNoAjax", "Home")')">Redirect not good with ajax - returns the page</a>
What it happens is the same: the ajax code calls the RedirectToAboutNoAjax , that redirects to about – and the result is the page. It is no redirect performed to the page itself – rather, on the ajax itself!And , to proof it, I will show the message of html returned in an message:
Third case( good with ajax): Call a action that returns the new url as a json data parameter and make javascript know that.The action:
[HttpPost] public ActionResult RedirectToAboutWithAjax() { try { //in a real world, here will be multiple database calls - or others return Json(new { ok = true, newurl = Url.Action("About") }); } catch (Exception ex) { //TODO: log return Json(new { ok = false, message = ex.Message }); } }
The javascript:
function AjaxGoodRedirect(urlAction) { $.ajax({ type: "POST", // see http://haacked.com/archive/2009/06/24/json-hijacking.aspx url: urlAction, data: {}, //to send data see more at http://bit.ly/mvc_ajax_jquery datatype: "JSON", contentType: "application/json; charset=utf-8", success: function (returndata) { if (returndata.ok) window.location = returndata.newurl; else window.alert(returndata.message); } } ); }
Note: You can combine the returning the RedirectToAction with Json by checking Request.IsAjaxRequest value and returning either FirstCase, either ThirdCase.
You can find the example for download here
If you want more details, please comment – and I will provide any further explanations.