views:

292

answers:

2

I'm trying to figure out how to show/hide links for users based on their roles. I know how to set the authorize attribute for an action method, but I'm having trouble making links show hide in a view if the user is say, an admin or a manager in my roles database.

Any good articles or code example someone can point me towards?

+4  A: 

In your view you can reference the IPrincipal user through the System.Web.Mvc.ViewPage's User property.

E.g. In your view you can have something like:

<% if (User.IsInRole("Admin")) { %>
    <%= Html.ActionLink("Admin only link", "Edit", "Users") %>
<% } %>

<% if (User.IsInRole("Manager") || User.IsInRole("Admin")) { %>
    <%= Html.ActionLink("Manager & Admin only link", "Edit", "Product") %>
<% } %>

HTHs,
Charles

Charlino
Thanks! Here's a twist - I have my tab links in the master page and I want a tab to appear for certain roles. Do you know how I can add a reference to my master for the IPrincipal?
Ben
Use either `HttpContext.Current.user` or `ViewContext.HttpContext.User` - that should do the trick :-)
Charlino
Ahh, now I can move on with things... I appreciate the help!
Ben
+1  A: 

This is one thing i really dont like with MVC (as in ASP.Net MVC, not the pattern) there is a tendancey to moving of UI logic into the markup.

There is no way to run Unit tests on that logic once its in the aspx.

Personly i think webforms with a suitable UI pattern (MVC or MVP etc) would better suit than having the page littered with conditional logic that cant be tested.

Patrick.B
As I still consider myself a beginner, I am getting better and better and I completely agree with what you are saying and have littered the heck out of my markup pages. I work in webforms at my day job and MVC on my freelance projects and have many conflicting headaches with learning both at the same time. Although I haven't learned much about how to unit test - I will no doubt need it one day in the near future; and I'm hoping by then the MVC team will have addressed this. Thanks for the comment +1 -ben
Ben