Reputation: 120
In my layout page i have used Request.IsAuthenticated method to show login and logout link.Login link poppup modal with the Login form.( modal popup is in partial page).
After successfully logged in logout link will show up. When i hit the logout l it goes to the logoff method and redirect to Index action but it doesn't goes to the view instead it shows same view. Pleaseadvise me. I have spend lots of hour to fixed this
Layout page
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
@if (Request.IsAuthenticated)
{
<div>
Loggen As: @User.Identity.Name
</div>
<a id="logOut" style="cursor:pointer">
<span class="glyphicon glyphicon-log-out"></span> Logout
</a>
}
else
{
<div>
Loggen As: @User.Identity.Name
</div>
<a style="cursor:pointer" data-toggle="modal" data-target="#loginModal">
<span class="glyphicon glyphicon-log-in"></span> Login
</a><h3>dsdasdasddsad</h3>
}
</li>
</ul>
</div>
</div>
</nav>
<div id="loginModal" class="modal fade" data-backdrop="static" data-keyboard="false" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Login</h4>
</div>
<div class="modal-body">
@Html.Partial("_LoginModal")
</div>
<div class="modal-footer">
<button id="Login" type="button" class="btn btn-success">Login</button>
<button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<section id="main">
@RenderBody()
<p>Copyright W3schools 2012. All Rights Reserved.</p>
</section>
<script type="text/javascript">
$('#logOut').click(function () {
$.post("@Url.Action("Logoff", "Home")", function (data) {
});
});
$('#Login').click(function (evt) {
evt.preventDefault();
var _this = $(this);
var _form = _this.closest("form");
var validator = $("form").validate();
var anyError = false;
$('#LoginForm').find("input").each(function () {
if (!validator.element(this)) {
anyError = true;
}
});
if (anyError)
return false;
var form = $('#LoginForm').serialize();
$.ajax({
type: "POST",
url: '/Home/Index',
data: form,
dataType: "json",
success: function (response) {
if (response.isRedirect && response.isUser) {
// alert('1');
window.location.href = response.redirectUrl;
}
else if (response.isRedirect && response.isAdmin) {
// alert('2');
window.location.href = response.redirectUrl;
}
else if (!response.isRedirect) {
$('#LoginForm').find("#message").text(response.errorMessage);
}
},
error: function (response) {
alert("Some error");
}
});
});
</script>
partial page: which is inside shared folder
@model WebApplication6.ViewModel.LoginViewModal
@using WebApplication6.ViewModel
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @id = "LoginForm", @class = "form-horizontal" }))
{
@Html.ValidationSummary(true, "Login failed. Check Login details")
<div class="form-group">
@Html.LabelFor(m => m.UserName, new { @class = "col-sm-3 control-label" })
<div class="col-sm-9">
@Html.TextBoxFor(x => x.UserName, new { @class = "form-control", @placeholder = "Enter UserName" })
@Html.ValidationMessageFor(x => x.UserName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-sm-3 control-label" })
<div class="col-sm-9">
@Html.PasswordFor(x => x.Password, new { @class = "form-control", @placeholder = "Enter UserName" })
@Html.ValidationMessageFor(x => x.Password)
</div>
</div>
<div class="form-group">
@Html.Label("User Type", new { @class = "col-sm-3 control-label" })
<div class="col-sm-3">
@Html.DropDownList("userType",
new SelectList(Enum.GetValues(typeof(UserType))), new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div id="message" style="color:#ff0000; font-weight:bold;" class="col-sm-offset-3 col-sm-12">
</div>
</div>
}
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebApplication4.Helper;
using WebApplication6.Models;
using WebApplication6.ViewModel;
namespace WebApplication6.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Index(LoginViewModal lm)
{
CareManagementEntities db = new CareManagementEntities();
if (ModelState.IsValid)
{
var userActive = db.Usrs.Where(x => x.Usr_Nm == lm.UserName && x.IsActive == true && x.IsDeleted == false).FirstOrDefault();
if (userActive != null)
{
var userss = db.Usrs.Where(x => x.Usr_Nm.ToLower() == lm.UserName.ToLower()).FirstOrDefault();
var validPassword = PasswordHelper.ValidatePassword(lm.Password, userss.Usr_Pwd);
if (validPassword)
{
var users = db.Usrs.Where(x => x.Usr_Nm == lm.UserName).FirstOrDefault();
if (users != null)
{
var userWithRole = db.Usrs.Where(x => x.Usr_Nm == lm.UserName && x.Usr_Role == lm.userType.ToString()).FirstOrDefault();
if (userWithRole != null)
{
if (userWithRole.Usr_Role == "Admin")
{
FormsAuthentication.SetAuthCookie(lm.UserName, false);
return Json(new
{
redirectUrl = "/Admin/Index",
isRedirect = true,
isAdmin = true,
});
}
else if (userWithRole.Usr_Role == "User")
{
return Json(new
{
redirectUrl = "/UserPage/Index",
isRedirect = true,
isUser = true,
});
}
else
{
return Json(new
{
isRedirect = false,
errorMessage = "The user name or password provided is incorrect."
});
}
}
else
{
return Json(new
{
isRedirect = false,
errorMessage = "The user name or password provided is incorrect."
});
}
}
}
else
{
return Json(new
{
isRedirect = false,
errorMessage = "The user name or password provided is incorrect."
});
}
}
else
{
return Json(new
{
isRedirect = false,
errorMessage = "The user name or password provided is incorrect."
});
}
}
return Json(new
{
isRedirect = false,
errorMessage = "Error happen please reload the page"
});
}
public ActionResult Logoff()
{
FormsAuthentication.SignOut();
Session.Abandon();
// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
cookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie2);
FormsAuthentication.RedirectToLoginPage();
return RedirectToAction("Index", "Home");
}
}
}
Upvotes: 1
Views: 660
Reputation: 120
I making an ajax call and ajax calls stay on the same page. So i replace the ajax call with action link that works for me.
Thank you Stephen Muecke for your quick right answer.
Upvotes: 1