在 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",则我收到错误
并非所有代码路径都返回值
.
如果我使用void",则无法返回任何内容.
If I use 'void', I cannot return anything.
即使我使用没有返回的void",由于 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?
推荐答案
return
通常从方法返回而不执行任何进一步的语句,因此不需要 else
部分.这样你就可以摆脱问题#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.
至于重定向为什么不返回某种redirect命令:
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屋!