locked
follow up question to roles in the _layout menu file RRS feed

  • Question

  • User1457412228 posted

    I asked this question 

    https://forums.asp.net/t/2157053.aspx?Proper+way+to+have+different+menus+based+on+roles

    but doing as the answer suggests seems to be less obvious than it at first appeared.

    If I am writing code in the _Layout file, how do I access the database?

    Also, I found this link, 

    https://social.technet.microsoft.com/wiki/contents/articles/51391.asp-net-core-2-0-user-role-base-dynamic-menu-using-dependency-injection.aspx

    and the last coding example at the bottom of the page shows them using @If(User.IsInRole("Admin") and that is the part that is not working correctly for me, so I cannot use this example.

    I have pasted the example code from the link.  For my _Layout file, , the "@If(User.IsInRole("Admin") does not appear to work consistently for my page, which is shown (and presumably works as expected) in this example.

    <div class="navbar-collapse collapse">
     <ul class="nav navbar-nav">
       <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
     @if (User.Identity.IsAuthenticated)
            {
                var UserRoles = "";
                if (@User.IsInRole("Admin"))
                {
                    UserRoles = "Admin";
                }
                else
                {
                    UserRoles = "Manager";
                }
      
                    @if (menus.GetMenuMaster(@UserRoles).Any())
                    {
                    @if (menus.GetMenuMaster(@UserRoles).Any())
                    {
                    @foreach (var menuNames in menus.GetMenuMaster(@UserRoles).Where(n => n.Parent_MenuID == "*"))
                    {
                            <li>
                                <a asp-area="" asp-controller=@menuNames.MenuURL asp-action=@menuNames.MenuFileName>@menuNames.MenuName</a>
                                <ul class="sub-menu">
                                    @foreach (var subMenu in menus.GetMenuMaster(@UserRoles).Where(n => n.Parent_MenuID == @menuNames.MenuID))
                                      {
                                        <li>
                                            <a asp-area="" asp-controller=@subMenu.MenuURL asp-action=@subMenu.MenuFileName>@subMenu.MenuName</a>
                                        </li>
                                       }
                                </ul>
                                </li>
                    }
                    }
                    }
                }
      </ul>

    thanks

    Friday, June 28, 2019 1:51 PM

Answers

All replies