Reputation: 2201
In my ASP.NET MVC 3 application, I have an action that is triggered through a jQuery AJAX POST request
. In this action, I check some DB data with the attributes, and if it passes the validation, I return a PartialView
result that is set inside a div on the view in the success
callback of the jQuery request. What I want to do is, if it does not pass validation, fully redirect the user to another page in my application.
I know I could do this through Javascript by passing a value to the view, and doing an extra check there, but I would like to know if it can be done on server-side.
Upvotes: 2
Views: 74
Reputation: 1039578
In your contorller action you could return either a PartialView
or a JsonResult
pointing to the controller action to redirect to:
public ActionResult SomeAction()
{
if (HasPassedValidation)
{
// everything went fine => let's return a partial view
// that will be updated
return PartialView();
}
// something went wrong with the validation =>
// we return a JsonResult pointing to the controller
// action we want to redirect to
var result = new
{
redirectTo = Url.Action("SomeOtherAction", "SomeController")
};
return Json(result, JsonRequestBehavior.AllowGet);
}
and then inside the success callback of your AJAX call test in which case you are and take respective steps:
success: function(result) {
if (result.redirectTo) {
// the controller action returned a JSON result => there was an error
// => let's redirect
window.location.href = result.redirectTo;
} else {
// everything went fine => let's update the DOM with the partial
$('#results').html(result);
}
}
Upvotes: 2
Reputation: 16149
The AJAX form control in MVC doesn't do a full redirect. The HTML one does, however. (Though it does mean you lose the async behavior).
Upvotes: 1