在asp.net mvc的4 jQuery的AJAX调用后,服务器端重定向 [英] Server side redirection after jquery ajax call in asp.net mvc 4
问题描述
我从一个jQuery AJAX调用发送登录信息到一个MVC 4控制器:
I am sending login information from a jQuery AJAX call to an 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");
}
});
如果登录成功,我想从服务器端将用户重定向到相应的页面用户类型的基础上。如果登录失败,一个字符串被发送回用户:
If the login is successful, I want to redirect a user from the server-side to the appropriate page on the basis of user type. If the login fails, a string is sent back to user:
[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',然后我得到的误差
不是所有code路径返回一个值
。
如果我使用'无效',我回不了任何东西。
If I use 'void', I cannot return anything.
即使我使用'无效',没有回报,我没有重定向到另一个控制器或视图由于jQuery的AJAX异步性要求。
Even if I use 'void' with no return, I am failing to redirect to other controller or view due to asynchronous nature of jQuery AJAX calls.
是否有任何技术来处理这样的场景?
Are there any techniques to handle such scenarios?
推荐答案
收益
通常是从方法返回,不执行任何进一步的陈述让其他不需要
部分。这样,您将摆脱的问题#1。
return
usually returns from method without executing any further statements in it so else
part is not needed. This way you will get rid of a problem #1.
至于重定向为什么不回到某种的重定向的命令:
As for redirecting why not return some kind of redirect command:
[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:
And then in 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;
}
});
这篇关于在asp.net mvc的4 jQuery的AJAX调用后,服务器端重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!