Show menu to logged in users in ASP.NET MVC 5

The _Layout.cshtml file contains a menu as follows. We want to hide some of the items in the menu based on logged in users.


The following code example shows the navigation menu for an ASP.NET application that uses forms authentication.


<ul class="main-nav">
    <li>
        <a href="~/">Home</a>
    </li>
    <li class="has-submenu">
        <a href="#">Customer <i class="fas fa-chevron-down"></i></a>
        <ul class="submenu">
            <li><a href="~/Customer/Create">Add Customer</a></li>
            <li><a href="~/Customer/Index">Show Customer</a></li>
        </ul>
    </li>
    <li class="has-submenu">
        <a href="#">Definition <i class="fas fa-chevron-down"></i></a>
        <ul class="submenu">
            <li><a href="#">Add Process</a></li>
            <li><a href="#">Add Application</a></li>
            <li><a href="#">Add Field</a></li>
        </ul>
    </li>
</ul>

You can try the following code snippet.


@if(User.Identity.IsAuthenticated)
{
  //...
  
  if(User.IsInRole("Admin"))
  {
    //...
  }
}
else
{
   //...
}

The final version of our code is as follows.


@if (User.Identity.IsAuthenticated)
{
    <ul class="main-nav">
        <li>
            <a href="~/">Home</a>
        </li>
        <li class="has-submenu">
            <a href="#">Customer <i class="fas fa-chevron-down"></i></a>
            <ul class="submenu">
                <li><a href="~/Customer/Create">Add Customer</a></li>
                <li><a href="~/Customer/Index">Show Customer</a></li>
            </ul>
        </li>
        <li class="has-submenu">
            <a href="#">Definition <i class="fas fa-chevron-down"></i></a>
            <ul class="submenu">
                <li><a href="#">Add Process</a></li>
                <li><a href="#">Add Application</a></li>
                <li><a href="#">Add Field</a></li>
            </ul>
        </li>

    </ul>
}

If you are logged in as a user, you can view the navigation menu as shown below.


show-menu-logged-in-aspnet-mvc-1.png

show-menu-logged-in-aspnet-mvc-2.png

Etiket : how to hide menu at login page in asp.net mvc, Show menu link based on logged in users, hide menu links to logged in users in ASP.NET MVC 5