jquery - asp.net mvc 4中jquery ajax调用后的服务器端重定向

标签 jquery ajax asp.net-mvc-4

我正在将登录信息从 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.
        }
    }

但是有问题:

  1. 如果此方法返回“ActionResult”,则会收到错误并非所有代码路径都返回值

  2. 如果我使用“void”,我将无法返回任何内容。

  3. 即使我使用不返回的“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/

相关文章:

jQuery getJSON 与 Django 发送错误的 sessionid cookie

javascript - 更改复选框+标签jquery

c# - CSS3 动画 无效果

c# - 我们如何使用 MVC 和 EntityFramework 中的下拉列表显示数据库的表名?

javascript - 有没有更好的方法来处理触摸设备上的 "hover"事件?

c# - 需要使用 jQuery getJSON 的工作示例

jquery - 在 JQuery 中动态创建表单并使用 JSON 发布它

javascript - Chrome 和 Firefox 会刷新除一个之外的所有 js 文件

javascript - 当网址不为空时歌曲无法播放

c# - 将 MVC4 模型转换为 cshtml 页面上的 javascript json 对象