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.