How do I do a redirect an Ajax Post in a Controller's Action Method?
Solution 1
return Json(new{data=true})
on the ajax success method
$.ajax({
type: 'POST',
url: 'your url',
data:your data
success: function (data) {
if (data) {
window.location.href="url";
}
else {
window.location.href="url";
}
},
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
return false;
Solution 2
You could do it like this :
Return a JSON result in both the cases, just return a false JSON reponse when your condition is false. In that way, your call will be returned to the AJAX on your view and then you can check the false value there and if matched, you can use javascript redirects to redirect to the appropriate view.
Hope this clears the idea that you want.
Solution 3
In Controller, return true or false in JSON. Then in AJAX success, if true, set window.location to new URL.
window.location = '@Url.Action("Index","Auth")';
SamIAm
Updated on June 26, 2022Comments
-
SamIAm almost 2 years
I have an Ajax POST being sent to one of my Controller. e.g.
Enquiry > Index.
In the Index() Action, I return an ActionResult of JSON.
As I am doing login checks, I do an if statement and if the activeUser's session token is null, I do a
return RedirectToAction("Index","Auth");
However, this is not redirecting properly but instead is returning the result in JSON which the browser complains about.
How do I set a redirect properly such that if the IF statement fails, it will go to the login page but otherwise it will return the JSON results that I require?
-
charlietfl almost 9 yearsyou would need to have the redirect done within the ajax success callback
-
Admin almost 9 yearsThe whole point of ajax calls is to stay on the same page. They do not redirect.
-
-
Unbreakable almost 7 yearsBut suppose we want to pass some data too. how to achieve that. I mean along with the 'url' we want to pass some data too.
-
Sriman Saswat Suvankar almost 7 yearsJust pass a data in Json format like data: { text : "hello"}.
-
Unbreakable almost 7 yearsI mean to say I want to pass data to the redirected page. I mean after the successful post. I want to pass some data to the window.location.href page
-
Siddhant Patra almost 7 yearsyou can pass the data by appending to the url.