RedirectToAction已命中但未重定向

时间:2019-03-06 12:52:51

标签: c# asp.net-mvc

我的重定向到操作击中了聊天室/索引控制器中的方法,但实际上并没有重定向用户,它仅保留在同一页面上。我该如何解决?我可以通过URL导航到视图,因此不会有任何错误。

会议室控制器

    [Authorize]
    public ActionResult ChatRoom()
    {
        return View();
    }

家庭控制器

  [AllowAnonymous]
  public ActionResult Index()
        {
            return View();
        }

    [HttpPost]
    [AllowAnonymous]
    public ActionResult Login(String username, String password)
    {
        bool ValidUser = UserDBController.ValidateUser(new Models.UserModel
        {
            UserName = username,
            PasswordHash = HashPass(password)
        });

        password = String.Empty;

        if (ValidUser)
        {
            FormsAuthentication.SetAuthCookie(username, true);
            return RedirectToAction("ChatRoom", "ChatRoom");
        }
        ViewBag.Username = username;
        return RedirectToAction("Index","Home");
    }

索引视图

    @{
    ViewBag.Title = "Home Page";
}

<div class="container">
    @Html.Partial("_LoginPartial")
</div>

部分登录

@{
    ViewBag.Title = "Login";
}


<div class="LoginForm">
    <div class="row">
        <div class="col-md-12 input">
            @Html.TextBox("Username", null, new { @class = "form-control", @id = "username", @placeholder = "Username", required = "required", value = !String.IsNullOrEmpty(ViewBag.username) ? ViewBag.username : "" })
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            @Html.TextBox("Password", null, new { @class = "form-control", @type = "password",  @id = "password", @placeholder = "Password", required = "required" })
        </div>
    </div>
    <button type="button" class="login-btn btn btn-primary">Login</button>
</div>

jQuery

$('.login-btn').click(function (e) {
    $.ajax({
        type: "POST",
        url: "/Home/Login",
        data: {
            userName: $('#username').val(),
            password: $('#password').val()
        }
    }).done(function (data) {
    });
});

2 个答案:

答案 0 :(得分:3)

那是因为您正在做ajax发布。您可以返回url作为结果,并使用该URL进行重定向。

答案 1 :(得分:2)

更改登录功能

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Login(String username, String password)
{
    ...

    if (ValidUser)
    {
        FormsAuthentication.SetAuthCookie(username, true);
        return Json(false, JsonRequestBehavior.AllowGet);
    }
    return Json(true, JsonRequestBehavior.AllowGet);
}

和您的AJAX方法

$('.login-btn').click(function (e) {
        $.ajax({
            type: "POST",
            url: "/Home/Login",
            data: {
                userName: $('#username').val(),
                password: $('#password').val()
            },
            succcess:function (myJSONdata) {
                if(myJSONdata == true)
                    location.href = '/ChatRoom/ChatRoom';
                else
                    location.href = '/Home/Index';
            }
        }).done(function (data) {
        });
});