ASP.Net MVC Hide/Show Menu Items Based On Security

后端 未结 3 966
小蘑菇
小蘑菇 2021-02-04 07:17

I\'m working on an ASP.Net MVC 3 site. The _Layout master view contains a menu and I want to hide some of the items in the menu based on if you are logged in and what roles you

3条回答
  •  野性不改
    2021-02-04 07:51

    Here is what I ended up doing. I created a helper class called MenuSecurity with static boolean properties for each menu item showing which items should be visible. Each property looked like this

    public static bool DashboardVisible
    {
       get 
       { 
          return 
             HttpContext.Current.User != null && 
             HttpContext.Current.User.Identity.IsAuthenticated; 
       }
    }
    

    I then tidied up my menu partial view to look like this

    @if (MenuSecurity.ReportsVisible){
  • @Html.ActionLink("Reports", "Index", "Reports")
  • } @if (MenuSecurity.DashboardVisible){
  • @Html.ActionLink("Dashboard", "Dashboard", "Admin")
  • } @if (MenuSecurity.AdminVisible){
  • @Html.ActionLink("Admin", "Index", "Admin")
  • }

提交回复
热议问题