我从jQuery AJAX调用发送登录信息到MVC 4控制器:
$.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调用的异步性质,我无法重定向到其他控制器或视图。
有没有办法处理这种情况?
解决方法
返回通常从方法返回,而不执行任何其他语句,否则不需要部分。这样你就可以摆脱一个问题#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,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;
}
});