Question

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.

Était-ce utile?

La 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");
}

Autres conseils

Should work with your line. May be you've made a mistake in word "Salesperson"?

I'd also advice to move this logic to controller:

public ActionResult YourAction()
{
  bool isAllowed = User.IsInRole("Manager")||User.IsInRole("Salesperson");
  ViewBag.isAllowed = isAllowed;

  ...
  return View();
}

Than in your View:

@if((bool)ViewBag.isAllowed)
{
    @Html.ActionLink("Sales Reports", "SalesReports", "Reports")
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top