How to hide tabs based on roles defined in attributes in MVC3?

By default, the tabs on the MVC3 website are created in the upper left corner. I would like to hide / show these tabs depending on whether the current user will have access to the ViewResult index. Allowed roles in ViewResult are defined by attributes. Is there a way to get the list of roles for ViewResult?

+7
source share
1 answer

If you ask (sorry, I wasn’t quite clear) about conditionally showing role-based HTML elements, you can do something like this:

@if (User.IsInRole("Administrators")) { @Html.ActionLink("Do Some Action", "DoAction", "SomeController") } 

If this is not what you are asking for, let me know.


Follow-up based on your comment:

Your question interests me, and I joked a bit and found that Vivien Chevalier has an interesting idea here , which essentially allows you to write something like this:

@Html.ActionLinkAuthorized("The Privilege Zone", "ThePrivilegeZone", "Home", true)

in your view, then check the action of the controller and either display the link or not.

In your controller example, you have an action similar to this:

 [Authorize(Roles = "Administrator")] public ActionResult ThePrivilegeZone() { return View(); } 

(I think the key point is that your View does not know squats about “Administrators” and relies on the extension code to make a heavy climb here:

 public static MvcHtmlString ActionLinkAuthorized( this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes, bool showActionLinkAsDisabled) { if (htmlHelper.ActionAuthorized(actionName, controllerName)) { return htmlHelper.ActionLink( linkText, actionName, controllerName, routeValues, htmlAttributes); } else { if (showActionLinkAsDisabled) { TagBuilder tagBuilder = new TagBuilder("span"); tagBuilder.InnerHtml = linkText; return MvcHtmlString.Create(tagBuilder.ToString()); } else { return MvcHtmlString.Empty; } } } 

Instead of cutting / pasting all this code here, you can take a look at it and see an example of the application that it received for this. I think it’s especially interesting for this approach that the view can display this PrivilegeZone link, but it only knows that something else will determine if this will be the case. Therefore, assuming that you have new requirements to allow people who were “Administrators” or “Owners” to access the link, you can change the controller’s action accordingly and not touch the view code. Interesting idea, at least for me.

+10
source

All Articles