Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing/Hiding Links in an ASP.Net MVC View

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?

like image 336
Ben Avatar asked Dec 07 '09 05:12

Ben


People also ask

How hide data in url in MVC?

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.

How to Add view in MVC visual studio 2022?

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.

How to Add view in ASP net Core MVC?

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.


2 Answers

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

like image 125
Charlino Avatar answered Sep 24 '22 07:09

Charlino


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.

like image 29
Patrick.B Avatar answered Sep 23 '22 07:09

Patrick.B