【发布时间】:2015-08-24 09:21:23
【问题描述】:
RedirectToAction 在使用 ajax 调用时“不起作用”,这是为什么呢?
登录操作通过 RedirectToAction 将我发送到操作索引,因此我可以看到该视图已返回。 AJAX 调用以done 结束。
为什么 URL 没有像我预期的那样更改为 ../home/index?
如果我在done 手动调用window.location.href = "/WebConsole53"; 我会得到我想要的重定向,但我宁愿在服务器上使用重定向。有人能找出问题所在吗?谢谢。
Ajax 调用:
$('#btnLogin').on('click', function() {
var url = urlHelper.getUrl('Account/login');
var data = {
username: $('#inputLoginUsername').val(),
password: $('#inputLoginPassword').val()
}
$.ajax({
url: url,
method: "POST",
data: data
})
.done(function (html) {
console.log('done login');
//window.location.href = "/mySite"; // this works
})
.fail(function (jqXhr, textStatus, errorThrown) {
console.log('failed');
});
});
行动:
[HttpPost]
[AllowAnonymous]
//[ValidateAntiForgeryToken]
public ActionResult Login(string username, string password/*, LoginViewModel model*/, string returnUrl)
{
//if (!ModelState.IsValid)
//{
// return View(model);
//}
// This doesn't count login failures towards account lockout To enable password failures to trigger account lockout, change to shouldLockout: true
//var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
//switch (result)
//{
// case SignInStatus.Success:
// return RedirectToLocal(returnUrl);
// case SignInStatus.LockedOut:
// return View("Lockout");
// case SignInStatus.RequiresVerification:
// return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
// case SignInStatus.Failure:
// default:
// ModelState.AddModelError("", "Invalid login attempt.");
// return View(model);
//}
return RedirectToAction("Index", "Home");
//return RedirectToActionPermanent("Index", "Home");
//return RedirectToLocal(returnUrl);
//return RedirectToAction("ShowDashboard", "Dashboard");
}
首页索引:
public ActionResult Index()
{
return View();
// return RedirectToAction("Login", "Account");
// return RedirectToAction("ShowDashboard", "Dashboard");
}
解决方案 - 全部归功于 @Stephen Muecke
使用来自 html.helper 的表单提交参见 doc here
@using (Html.BeginForm("login", "Account"))
{
@Html.TextBox("Name");
@Html.Password("Password");
<input type="submit" value="Sign In">
}
【问题讨论】:
-
因为 ajax 调用的全部意义在于保持在同一页面上——它们不会重定向。如果要重定向,则进行正常提交(使用ajax没有意义)
-
我只知道从客户端到服务器的一种方法,它是通过 AJAX 调用。
-
我的意思是已经使用了表单提交(如果这算作正常提交的话),但我认为他们在后台也使用了 AJAX。
-
只需在表单中添加
<input type="submit">并使用绑定到模型属性的强类型 html 助手正确构建 html 并回发模型(使用LoginViewModel model,而不是单个参数) - 没有 javascript需要 /jquery! -
我想我明白了。有道理。我以前做过几次。我从来没有对我猜想的不同之处进行更深入的思考,或者我可能只是度过了糟糕的一天。非常感谢,再次帮助我。
标签: asp.net ajax asp.net-mvc asp.net-mvc-3 asp.net-mvc-5