Search code examples
c#asp.net-mvcasp.net-mvc-3asp.net-mvc-4simplemembership

Check UserRole and set Permission in Layout


Suppose I have a actionlink in the layout, which I want to show, if the logged-in user is in either of the two roles "Manager" or "Salesperson", then how do I do that? What I have been doing is as follows:-

@if((User.IsInRole("Manager"))||(User.IsInRole("Salesperson")))
{
    @Html.ActionLink("Sales Reports", "SalesReports", "Reports")
}

Unfortunately, the above line of code is not working. The link "Sales Reports" is not visible to users with role "Salesperson". I want to make the link "Sales Reports" visible only to users in "Manager" role or in "Salesperson" role. Kindly advise how to go about it? Thank You.


Solution

  • The MVC way of doing things rolebased is by using [Authorize] attribute for the action or controller. You can then say whch roles are granted as follows:

    [Authorize(Roles="Manager,Salesperson")]
    

    You can perhaps create a partial view which contains these actions and show the one based on the users role.

    [Authorize(Roles="Manager,Salesperson")]
    public ActionResult NavigationLinks()
    {
         return View("PATH TO PARTIAL");
    }