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?
You can't hide url parameters. If the reason you want the parameter hidden is so that people can't access ids they are not authorised to, then the solution is to amend your code so that people only access data they are authorised to access. Please Sign up or sign in to vote.
Right click the Views\HelloWorld folder and click Add, then click MVC 5 View Page with Layout (Razor). In the Specify Name for Item dialog box, enter Index, and then click OK. In the Select a Layout Page dialog, accept the default _Layout.
Right-click on the Views folder, and then Add > New Folder and name the folder HelloWorld. Right-click on the Views/HelloWorld folder, and then Add > New Item. In the Add New Item - MvcMovie dialog: In the search box in the upper-right, enter view.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With