jQuery之后的服务器端重定向ajax在asp.net mvc中调用4

我从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;
  }
 });

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...