Search code examples
asp.net-corerazorrazor-pages

Display Admin menu only when in Admin area and authorized?


In _Layout.cshtml, I have added Admin menu.

enter image description here

How can I make it displayed only when one is in Admin area and when one is authorized?

I did not try anything as I don't know what to try.


Solution

  • You can use this code to achieve it.

    _Layout.cshtml

       @{
            //get the value of Area
            var route = ViewContext.RouteData.Values["area"]?.ToString();
            var admin = "Admin";
            var result = Context.User.Identity.IsAuthenticated;
            
        }
    
        
        @if (admin.Equals(route) && result )
        { 
            <div class="admin-menu">
                ......
            </div> 
        }
    
         <div class="container">
            <main role="main" class="pb-3">
                @RenderBody()
            </main>
        </div>
    

    Demo:

    check this simple demo, I use Test!!! as the menu, Only the one is authorized and in admin area can see this menu:

    enter image description here