Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide and visible the div tags of Layout.cshtml on the basis of user role in Asp.net MVC4(Razor)

I am having a master page which is having some menus for a Role called user and other menus are for the role of Admin, So what i am willing is to check the role of the user and and show some div tags and hide others on the basis of user role.

As, we don't have controller for layout.cshtml, so how i can set the viewModel for layout view Wherein i can check the role of the current user

How to do role based checking on the layout.cshtml.

I have been through followin question but it has not been answered by now

How to Show or hide controls based on roles - ASP.NET MVC 4 Razor

So,Please tell me the possible solution and which way would be the best for applying role based checking in layout.cshtml

like image 365
Yogesh Avatar asked Dec 08 '22 16:12

Yogesh


2 Answers

You could use the User.IsInRole method:

@if (User.IsInRole("admin"))
{
    <li>Only the admin can see this menu item</li>
}
like image 167
Darin Dimitrov Avatar answered Feb 17 '23 03:02

Darin Dimitrov


You can use Following code for role based checking

@if(Request.IsAuthenticated)

{
    if(User.IsInRole("Admin")
    {
     <Ul Class="SubMenuItem">

     <li> this menu item is for Admin role</li>
     </Ul>
    }
     if(User.IsInRole("User")
    {
     <Ul Class="SubMenuItem">

     <li> this menu item is for User role</li>
     </Ul>
    }
}

For unknown user

else
{
 <Ul Class="SubMenuItem">

     <li> this menu item is for Unknown user</li>
     </Ul>
}
like image 24
Yogesh Avatar answered Feb 17 '23 05:02

Yogesh