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

后端 未结 3 972
小蘑菇
小蘑菇 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:32

    Create a partial view and return the view from the controller:

    LayoutViewModel.cs:

    public class LayoutViewModel
    {   ...
        public bool ShowAdmin { get; set; }
    }
    

    LayoutController.cs:

    public PartialViewResult GetAdminMenu()
        {
            LayoutViewModel model = new LayoutViewModel();            
    
            model.ShowAdmin = userHasPermission("Admin"); // change the code here
    
            return PartialView("_AdminMenu", model);
        }
    

    _AdminMenu.cshtml (partial view):

    @model DelegatePortal.ViewModels.LayoutViewModel
    
    
    @if (@Model.ShowAdmin)
    {
       
    }
    

    _Layout.csthml (main view):

    ...
                  @Html.Action("GetAdminMenu", "Layout")
    

提交回复
热议问题