nacho10f
nacho10f

Reputation: 5886

Help with asp.net mvc authorization

Say you want to display a menu that has many elements... Some elements are exclusive to users with "administrator" role. I know how to restrict controllers methods using

[Authorize(Roles = "Administrators")]

but I want to figure out a way to display a specific html thing depending on the user roles

example

<ul>
<li>Menu Item 1</li>
<% //if is admin%>
<li>Menu Item 2 (for admins only)</li>
</ul>

How do I do thiis?

Upvotes: 0

Views: 417

Answers (2)

G-Wiz
G-Wiz

Reputation: 7426

Two ways to do this. If you pass your list items into the View via ViewData then your action would look like this:

public ViewResult Menu() {
  var list = new string[]{ "Menu Item 1" };
  if(HttpContext.User.IsInRole("Administrators"))
    list.Add(Menu Item 2 (for admins only)");
  ViewData["MenuItems"] = list;
  return View();
}

Otherwise you could simply set a value in your ViewData to indicate to the view if the it should display admin values.

public ViewResult Menu() {
  ViewData["DisplayAdminItems"] = HttpContext.User.IsInRoles("Administrators");
}

You don't want to use the Authorize filter because you want to allow non-admins to access that action. I guess alternatively you can have two actions, one that is has the Authorize filter and one that doesn't. However that forces all links and redirects to those actions to decide which one to use.

Upvotes: 2

dso
dso

Reputation: 9580

<ul>
<li>Menu Item 1</li>
<% if(Roles.IsUserInRole("Administrators")) { %>
<li>Menu Item 2 (for admins only)</li>
<% } %>
</ul>

Upvotes: 3

Related Questions