开发者

LoginView control analogue in ASP.NET MVC

开发者 https://www.devze.com 2023-03-13 14:45 出处:网络
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

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()
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号