ASP.Net MVC 5 Check User Role for _Layout

Posted by: tranhau102495 on 1 April 2019, 8:11 pm EST

  • Posted 1 April 2019, 8:11 pm EST

    Hello everyone I am trying to check what Role my user is in with the default setup.
    I thought I would only need 'User.IsInRole("User")' for in my View but its not so easy.
    I want to display certain links depending on the role for the user.
    Here is what I have and I tried a few different options.
    I have the default setup database and some added tables that dont matter for this part.
    Request.IsAuthenticated works for login.

    01
    @if (Request.IsAuthenticated)
    02
    {
    03
    <li class="nav-item">
    04
    <a class="nav-link" href="#">Assign Roles</a>
    05
    </li>
    06
    <li class="nav-item">
    07
    <a class="nav-link" href="#">View Roles</a>
    08
    </li>
    09
    } else if (Request.IsAuthenticated && User.IsInRole("User"))
    10
    {
    11
    <li class="nav-item">
    12
    <a class="nav-link" href="#">user Else clause</a>
    13
    </li>
    14
    } else if (Request.IsAuthenticated && User.IsInRole("Guest"))
    15
    {
    16
    <li class="nav-item">
    17
    <a class="nav-link" href="#">Guest Else clause</a>
    18
    </li>
    19
    } else
    20
    {
    21
    <li class="nav-item">
    22
    <a class="nav-link" href="#">else else!! Else clause</a>
    23
    </li>
    24
    }
  • Replied 3 April 2019, 2:24 am EST

    Hi,
    Please refer to the following article, this might be helpful in your requirement fulfillment.
    https://www.c-sharpcorner.com/article/dynamic-menu-bind-depends-on-user-role-in-asp-mvc/
    Regards,
    Manish Gupta
Need extra support?

Upgrade your support plan and get personal unlimited phone support with our customer engagement team

Learn More

Forum Channels