我从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; } });
原文地址:https://www.jb51.cc/jquery/181786.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。