I am trying to hide a link or would not be able to go to the page if the user is not an administrator. I am able to do the latter using this code in my controller:
[AuthorizeRoles("Admin")]
public ActionResult Registration()
{
return View();
}
When I try to hide the link using this code:
@if (!Context.User.Identity.Name.IsEmpty())
{
<li id="dd_vehicle" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">VEHICLE <b class="caret"></b></a>
<ul class="dropdown-menu">
@if (ViewContext.HttpContext.User.IsInRole("Admin"))
{
<li id="item_registration">
@Html.ActionLink("Registration", "Registration", "Home")
</li>
}
}
The link gets hidden. But when I login as "Admin", still the link doesn't show.
This is how I AuthorizeAttribute:
public class AuthorizeRolesAttribute : AuthorizeAttribute
{
private readonly string[] userAssignedRoles;
public AuthorizeRolesAttribute(params string[] roles)
{
this.userAssignedRoles = roles;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool authorize = false;
using (var db = new SMBI_DBEntities())
{
var um = new UserManager();
foreach (var roles in userAssignedRoles)
{
authorize = um.IsUserInRole(httpContext.User.Identity.Name, roles);
if (authorize)
return authorize;
}
}
return authorize;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("~/Home/UnAuthorized");
}
}
and this is in LoginView:
[HttpPost]
public ActionResult Login(UserLoginView ulv, string returnUrl)
{
if (ModelState.IsValid)
{
var um = new UserManager();
var password = um.GetUserPassword(ulv.LoginName);
if (string.IsNullOrEmpty(password))
{
ModelState.AddModelError("", "Login ID and Pasword do not match.");
}
else
{
if (ulv.Password.Equals(password))
{
FormsAuthentication.SetAuthCookie(ulv.LoginName, false);
return RedirectToAction("Registration", "Home");
}
else
{
ModelState.AddModelError("","Password provided is incorrect.");
}
}
}
return View(ulv);
}
Hope you could help. Thank you.