How do you do condition开发者_如何学Goal content rendering in ASP.NET MVC depending on User.IsInRole()
? Tried all matches i could find here, at SO but still not satisfied. I need to hide action links depending on user roles so first i thought of a helper like
public static MvcHtmlString ActionLink(this HtmlHelper html, string linkUrl, string linkText, object htmlAttributes, bool alwaysVisible, params string[] roles)
but then I realized that I often needed to hide the outer content too (for example, <li></li>
in the menu where my links were placed into). I follow the recommendation from best practices and have UrlHelperExtension
so my typical links look like:
<a href="@Url.SomeStuff()">some stuff</a>
and I can't try the idea to implement the helper over RouteLink()
that will grab AuthorizeAttribute
from appropriate controller methods can I?. What's your solution?
I tend to use something along the lines of:
@if (User.IsInRole("Role")) {
<li>
<a href="@Url.SomeStuff()">Some stuff</a>
<li>
}
This way I can have multiple links per role if needed.
Another way you could possibly approach this is by using either CSS to hide the elements you want hidden based on roles e.g.
<li class=@(User.IsInRole('role')?"showClass":"hideClass")>
<a href="@Url.SomeStuff()">Some stuff</a>
<li>
or perhaps something with Jquery, such as:
<li class="@User.Role")>
<a href="@Url.SomeStuff()">Some stuff</a>
<li>
$(document).ready(function () {
$(".SomeRole").hide()
}
精彩评论