在我的 ASP.NET MVC 3 应用程序中,我有一个通过 jQuery AJAX POST 请求
触发的操作。在此操作中,我使用属性检查一些数据库数据,如果通过验证,我将返回一个 PartialView
结果,该结果设置在 success
中 View 上的 div 内> jQuery 请求的回调。我想要做的是,如果未通过验证,则将用户完全重定向到我的应用程序中的另一个页面。
我知道我可以通过 Javascript 通过向 View 传递一个值并在那里进行额外的检查来完成此操作,但我想知道是否可以在服务器端完成。
最佳答案
在您的 Controller 操作中,您可以返回一个 PartialView
或 JsonResult
指向要重定向到的 Controller 操作:
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);
}
然后在 AJAX 调用测试的成功回调中,在这种情况下,您将采取相应的步骤:
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);
}
}
关于jquery - 从 Action 进行完整重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12565966/