RedirectToAction被击中但没有重定向

问题描述 投票:0回答:2

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

聊天室控制器

    [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) {
    });
});
c# asp.net-mvc
2个回答
3
投票

那是因为你正在做ajax帖子。您可以返回url作为结果并使用该URL重定向。


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) {
        });
});
© www.soinside.com 2019 - 2024. All rights reserved.