【问题标题】:RedirectToAction doesn't happen when I start with an AJAX call当我从 AJAX 调用开始时,不会发生 RedirectToAction
【发布时间】: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。
  • 只需在表单中添加&lt;input type="submit"&gt; 并使用绑定到模型属性的强类型 html 助手正确构建 html 并回发模型(使用 LoginViewModel model,而不是单个参数) - 没有 javascript需要 /jquery!
  • 我想我明白了。有道理。我以前做过几次。我从来没有对我猜想的不同之处进行更深入的思考,或者我可能只是度过了糟糕的一天。非常感谢,再次帮助我。

标签: asp.net ajax asp.net-mvc asp.net-mvc-3 asp.net-mvc-5


【解决方案1】:

根据 cmets;这并不是真正的最佳做法。但是,为了回答您的问题,重定向不会发生,因为浏览器没有直接处理响应。您在成功方法中处理响应。

如果您想通过服务器指定的 AJAX 调用进行重定向,您可以使用以下命令:

$.ajax({
    url: url,
    method: "POST",
    data: data,
    success: function (data) {
        $("body").html(data);    //Providing the result is a response to redirect ONLY
    }
})

实际上,您只是用响应覆盖整个正文,然后浏览器在实际呈现任何内容之前将其作为重定向拾取。

但是,如果您采用这种方法,您可能想要满足其他状态代码,很明显是 500,因为如果您这样做并且存在内部错误;除了记录到浏览器控制台之外什么都不会发生

【讨论】:

  • 这是我通常的做法。从 AJAX 调用返回 html 以设置一些 div。这不是我这次要找的。这次我想调用我的服务器操作,进行一些登录验证,如果顺利,重定向到用户可以继续的另一个操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
相关资源
最近更新 更多