Content based on the asp.net mvc role

I want to display content depending on the specified role (s) of the active user in ASP.NET MVC.

Compare the old way using WebForms:

protected void Page_Load(Object sender, EventArgs e) { if(User.IsInRole("Administrator")) { adminLink.Visible = true; } } 

Now, how will I write this when using ASP.NET MVC? From my point of view, it would be wrong to place it directly in the view file, and assigning a variable for each individual view will also not.

+4
source share
4 answers

Create an Html helper and check the current roles of the user in his code:

 public static class Html { public static string Admin(this HtmlHelper html) { var user = html.ViewContext.HttpContext.User; if (!user.IsInRole("Administrator")) { // display nothing return String.Empty; // or maybe another link ? } var a = new TagBuilder("a"); a["href"] = "#"; a.SetInnerText("Admin"); var div = new TagBuilder("div") { InnerHtml = a.ToString(TagRenderMode.Normal); } return div.ToString(TagRenderMode.Normal); } } 

UPDATED:

Or create a wrapper for a helper. Example for ActionLink (this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName):

 public static class Html { public static string RoleActionLink(this HtmlHelper html, string role, string linkText, string actionName, string controllerName) { return html.ViewContext.HttpContext.User.IsInRole(role) ? html.ActionLink(linkText, actionName, controllerName) : String.Empty; } } 
+8
source

No, you would place it in a view file, as you actually would:

 <% If (User.IsInRole("Administrator")) { %> <div>Admin text</div> <% } %> 
+3
source

this worked for me:

  <% MembershipUser mu = Membership.GetUser(); if (mu != null) if (Roles.IsUserInRole(mu.UserName, "Administrator")) { %> <li class="paddingleftThree"><%= Html.ActionLink("User Administration", "GetUsers", "Account")%></li> <%} %> 
+1
source

Separation of approach The approach proposed in ASP.NET MVC 4 How do you serve different role-based HTML? in my opinion this is the best way to go.

Personally, I avoid IsInRole checking the code as much as possible and leaving it a declarative tool to limit the role as much as possible. This ensures that the code will persist over time. I'm not sure if this is the right or wrong approach, but I worked well for me.

0
source

All Articles