Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you are asking (sorry, wasn't clear exactly to me) about conditional showing of HTML elements based on roles, you <em>could</em> do something like this:</p> <pre><code>@if (User.IsInRole("Administrators")) { @Html.ActionLink("Do Some Action", "DoAction", "SomeController") } </code></pre> <p>If that isn't what you're asking, let me know.</p> <hr> <p><strong>Follow-up based on your comment:</strong></p> <p>Your question interests me and I did a little poking around and found that Vivien Chevallier has an interesting idea <a href="http://www.vivienchevallier.com/Articles/create-an-authorized-action-link-extension-for-aspnet-mvc-3" rel="nofollow noreferrer">here</a> which essentially lets you write something like so:</p> <p><code>@Html.ActionLinkAuthorized("The Privilege Zone", "ThePrivilegeZone", "Home", true)</code></p> <p>in your View and then this check the controller action and either renders a link or doesn't.</p> <p>In his controller example, you've got an action like this:</p> <pre><code>[Authorize(Roles = "Administrator")] public ActionResult ThePrivilegeZone() { return View(); } </code></pre> <p>(I guess the key point here is that your View doesn't know squat about "Administrators" and relies upon the extension code to do the heavy lifting here:</p> <pre><code>public static MvcHtmlString ActionLinkAuthorized( this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary&lt;string, object&gt; 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; } } } </code></pre> <p>Rather than cut/paste all of that code here, you can take a look at it and see the example application he's got for that. I think what's particularly interesting to this approach is that the view <em>could</em> display that PrivilegeZone link but knows only that something else will determine whether that's the case. So, assuming that you got new requirements to only allow folks who were "Administrators" or "Owners" to have access to the link, you could modify the controller action accordingly and not touch the view code. Interesting idea, at least to me.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload