我正在将登录信息从 jQuery AJAX 调用发送到 MVC 4 Controller :
$.post(url, data, function (response) {
if (response=='InvalidLogin') {
//show invalid login
}
else if (response == 'Error') {
//show error
}
else {
//redirecting to main page from here for the time being.
window.location.replace("http://localhost:1378/Dashboard/Index");
}
});
如果登录成功,我想根据用户类型将用户从服务器端重定向到适当的页面。如果登录失败,则会向用户发送回一个字符串:
[HttpPost]
public ActionResult Index(LoginModel loginData)
{
if (login fails)
{
return Json("InvalidLogin", JsonRequestBehavior.AllowGet);
}
else
{
// I want to redirect to another controller, view, or action depending
// on user type.
}
}
但是有问题:
如果此方法返回“ActionResult”,则会收到错误
并非所有代码路径都返回值
。如果我使用“void”,我将无法返回任何内容。
即使我使用不返回的“void”,由于 jQuery AJAX 调用的异步特性,我也无法重定向到其他 Controller 或 View 。
有什么技术可以处理这种情况吗?
最佳答案
return
通常从方法返回,而不执行其中的任何进一步语句,因此不需要 else
部分。这样你就可以解决问题#1。
至于重定向,为什么不返回某种重定向命令:
[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")});
}
然后在 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;
}
});
关于jquery - asp.net mvc 4中jquery ajax调用后的服务器端重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19795198/