In my App I have navbar with menu. In menu I have 3 dropdowns.
Access is restricted but menus
I see your roles is static, because you check if(RoleId==1)
so that user is admin. I think you can define roles like enum
.
public enum UserRole
{
User = 1,
Manager = 2,
Admin = 3,
//SuperAdmin...etc.
}
Create base controller, add CurrentUser property. And when action execute take current user.
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
CurrentUser = db.GetLoggedUserFromDatabase(); // to use in controller
ViewBag.CurrentUser = CurrentUser; // to use in views
}
public User CurrentUser { get; set; }
}
Finally your controller implements BaseController
:
public class AnyController : BaseController
{
//in every action you have current user's details.
//Already you know current users role. you can use it. for example:
public ActionResult AnyAction()
{
if(CurrentUser != null) //if user logged
{
if (CurrentUser.Role == (int)UserRole.Admin)
{
//user is admin
}
}
}
}
In views you can use ViewBag.CurrentUser
. Cast it first then check role as in controller.