Modify _layout for different users

后端 未结 1 1706
说谎
说谎 2021-01-26 06:33

In my App I have navbar with menu. In menu I have 3 dropdowns.

  • public
  • for normal users
  • for admins

Access is restricted but menus

相关标签:
1条回答
  • 2021-01-26 06:56

    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.

    0 讨论(0)
提交回复
热议问题