Scifiballer24
Scifiballer24

Reputation: 593

How do you restrict certain HTML elements to certain roles using ASP.NET MVC?

I'm looking for the standard practice in specifying that a certain HTML element, like a "Create user" button should only be displayed when the user is logged-in and belongs to the role "Administrator."

For example, using Spring MVC in Java, the Spring Security tag library has a control that does just that:

<sec:authorize access="hasRole('ROLE_PRESIDENT')">
    <input type="button" value="Launch nuclear weapons"/>
</sec:authorize>

Whatever appears between the tags will only display when the user belongs to the role specified.

Does ASP.NET MVC have such feature?

Upvotes: 6

Views: 2414

Answers (3)

rick schott
rick schott

Reputation: 20617

If you need element level security across your site, I suggest you create custom HtmlHelpers per element that all implement your security rules for rendering.

Note: wrapping if statements with role checks all over your views will not be maintainable

Upvotes: 3

Ashok Padmanabhan
Ashok Padmanabhan

Reputation: 2120

@If User.IsInRole("Administrator") Then 'whatever end if

something like should work

Upvotes: 0

Jon
Jon

Reputation: 16718

For Razor view engine:

@if (User.IsInRole("ROLE_PRESIDENT")) {
    <input type="button" value="launch nuclear weapons" />
}

For Webforms view engine:

<% if (User.IsInRole("ROLE_PRESIDENT")) { %>
    <input type="button" value="launch nuclear weapons" />
<% } %>

Upvotes: 5

Related Questions