Question

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?)

Was it helpful?

Solution

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.

OTHER TIPS

I new this existed, but took a while to find. Here's what I am using:

<asp:LoginView runat="server">
    <AnonymousTemplate>
        You are not logged in yet. Please log in.
    </AnonymousTemplate>
    <RoleGroups>
        <asp:RoleGroup Roles="Admin">
            <ContentTemplate>
                You are an Admin.
            </ContentTemplate>
        </asp:RoleGroup>
        <asp:RoleGroup Roles="Customers">
            <ContentTemplate>
                You are a customer.
            </ContentTemplate>
        </asp:RoleGroup>
    </RoleGroups>
    <LoggedInTemplate>
        Simple Log in check
    </LoggedInTemplate>
</asp:LoginView>

This allows you to show different content to different users based on their login state or credentials.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top