Reputation: 129
My redirect to action hits the method in the chatroom / index controllers but doesn't actually redirect the user, it just remains on the same page. How do i fix this? I can navigate to the views via the urls so there are no errors with regards to that.
Chatroom controller
[Authorize]
public ActionResult ChatRoom()
{
return View();
}
Home Controller
[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");
}
Index View
@{
ViewBag.Title = "Home Page";
}
<div class="container">
@Html.Partial("_LoginPartial")
</div>
Login partial
@{
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) {
});
});
Upvotes: 0
Views: 231
Reputation: 1939
Change your Login function
[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);
}
and your AJAX method
$('.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) {
});
});
Upvotes: 2
Reputation: 3214
That's because you are doing ajax post. You can return url as a result and use that url to redirect.
Upvotes: 3