Showing/Hiding Links in an ASP.Net MVC View

10,032

Solution 1

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

Solution 2

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.

Solution 3

<% if(HttpContext.Current.User.IsInRole("Admin")){%> <a href="/Admin">Admin</a> <% } %>

Use this code. This is easier.

Share:
10,032
Ben
Author by

Ben

I'm very new to programming and I'm learning ASP.net MVC. I expect at first I'll be asking more than responding, but I hope to get up to speed soon and start helping others.

Updated on June 13, 2022

Comments

  • Ben
    Ben almost 2 years

    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?

  • Ben
    Ben over 14 years
    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?
  • Charlino
    Charlino over 14 years
    Use either HttpContext.Current.user or ViewContext.HttpContext.User - that should do the trick :-)
  • Ben
    Ben over 14 years
    Ahh, now I can move on with things... I appreciate the help!
  • Ben
    Ben over 13 years
    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
  • Bob
    Bob over 11 years
    Use Selenium for UI testing. You can run tests using different roles and then test for the existence of HTML controls (hey that rhymes).