Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding links from certain roles in ASP.NET MVC5

So this may sound a dumb question, but how do I show a link only for an admin user?

Suppose an ordinary user sees the following links:
Home / About / Contact

And an admin user sees the following links:
Home / About / Contact / Admin

I tried restricting in the controller and linking the controller on the menu. But it still shows the link for everyone, just doesn't allow access to anyone but admin

Can the views be overloaded?

like image 412
user60812 Avatar asked Aug 20 '13 21:08

user60812


1 Answers

Depending on what sort of Membership/User provider you are using, you should just be able to check directly from the View if the user is logged in and in the specific role.

So you would end up with something like;

@Html.ActionLink("Index", "Home") 
@Html.ActionLink("About", "Home") 
@Html.ActionLink("Contact", "Home") 
@if ( User.Identity.IsAuthenticated ){
    if ( User.IsInRole("Admin") ){
        @Html.ActionLink("Admin", "AdminController")        
    }
}

And remember to add [Authorize] attribute to your Admin action method:

[Authorize(Roles="Admin")]
public ActionResult Admin()
{
    // ...
    return View();
}
like image 192
Tim B James Avatar answered Oct 02 '22 14:10

Tim B James