Server side redirection after jquery ajax call in asp.net mvc 4
return
usually returns from method without executing any further statements in it so else
part is not needed. This way you will get rid of a problem #1.
As for redirecting why not return some kind of redirect command:
[HttpPost]public ActionResult Index(LoginModel loginData){ if (login fails) { return Json(new {result = "InvalidLogin"}, JsonRequestBehavior.AllowGet); } return Json(new {result = "Redirect", url = Url.Action("MyAction", "MyController")});}
And then in javascript:
$.post(url, data, function (response) { if (response.result == 'InvalidLogin') { //show invalid login } else if (response.result == 'Error') { //show error } else if (response.result == 'Redirect'){ //redirecting to main page from here for the time being. window.location = response.url; } });
This help me.
return JavaScript("window.location = '/'");
Ref. linkHow to get an ASP.NET MVC Ajax response to redirect to new page...
I had to do this but none of the solutions I found really satisfied my extreme requirements of JavaScript parsing errors that I had to avoid in order to redirect the client to the login page.
What I did was to send a simple "NOAUTH" string response from my custom Authorization attribute, then intercept the Ajax response before any event handlers are hit, and redirect the user by setting window.location.
Server side:
protected override void HandleUnauthorizedRequest(AuthorizationContext context){ if (context.RequestContext.HttpContext.Request.IsAjaxRequest()) { var result = new ContentResult {Content = "NOAUTH"}; context.Result = result; return; }}
Then on the client side:
$.ajaxSetup({ dataFilter: function (data, type) { if (data !== "" && data === "NOAUTH") { window.location = '/'; } return data; }});
I would not recommend this approach though. If you have to do this, then I would at-least suggest instead putting the "NOAUTH" value inside the http response header, then read the value in a global JQuery complete handler.
Server side:
HttpContext.Current.Response.AddHeader("NOAUTH", "1");
Client-side:
$.ajaxSetup({ complete: function (jqXHR, textStatus) { if (jqXHR.getResponseHeader("NOAUTH") === '1') window.location = '/'; }});
Note that using dataFilter is the only way to intercept ajax requests before any other of your event handlers are hit.