Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC How to apply role-based or authentication-based View rendering?

i want to show/hide certain parts of a View based on Authentication-status or Roles. For my controller actions I have extended ActionFilterAttribute so I can attribute certain Actions.

<RequiresRole(Role:="Admin")> _
Function Action() as ActionResult
    Return View()
End Function

Is there a similar way (attributing) which I can use in the Views? (so not like this: How can I create a view that has different displays according to the role the user is in?)

like image 277
Ropstah Avatar asked Apr 29 '09 12:04

Ropstah


People also ask

How is role-based authorization implemented in ASP NET?

To accomplish this, start by adding a Web. config file to the Roles folder. The <authorization> element in the <system. web> section indicates that only users in the Administrators role may access the ASP.NET resources in the Roles directory.


1 Answers

You can access the user's logged-in roles from the view like this:

<% if (Page.User.IsInRole("Admin")) { %>
        <td>
          <%= Html.DeleteButton("delete", model.ID) %>
        </td>
<% } %>

and maybe your extension method with something like:

public static string DeleteButton(this HtmlHelper html, 
    string linkText, int id)
{
    return html.RouteLink(linkText,
     new { ID = id, action = "Delete" },
     new { onclick = "$.delete(this.href, deleteCompleted()); return false;" });
}

Obviously, I'm using JavaScript to perform an HTTP DELETE to my controller action, to prevent page crawlers from accidentally deleting data from getting my pages. In my case I'm extending JQuery with a delete() method to supplement the HTTP verb.

like image 116
Kris Avatar answered Oct 13 '22 01:10

Kris