Mr Lahey
Mr Lahey

Reputation: 676

Authorizing sections of a view in MVC

I was wondering if it's possible to authorize parts of a view inside the view.

For example, I understand how to authorize the entire controller in this method

<HandleError()> _
Public Class HomeController
  Inherits System.Web.Mvc.Controller

  Function Index()
    Return View()
  End Function

  <Authorize(Roles:="Administrators")> _
  Function AdministratorSecrets()
    Return View()
  End Function

End Class

But what Id like to do is have it so if the admin is logged in, they can see additional links in my navigation.

Something along the lines of

            <ul id="menu">              
                <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
                <li><%= Html.ActionLink("About", "About", "Home")%></li>
                <Authorize(Roles:="Administrators")> _
                <li><%= Html.ActionLink("Admin", "Admin", "Home")%></li>
            </ul>

Obviously that won't work, but it gives an idea of what I'm trying to accomplish.

Any ideas?

Upvotes: 3

Views: 3793

Answers (2)

bearing09
bearing09

Reputation: 739

It's the best practice to send the if stuff to the new html helper extension method.

Upvotes: 0

Paul
Paul

Reputation: 6218

Use something like this:

<% if(Roles.IsUserInRole("Administrator")){ %>
<span>HTML Code</span>
<% } %>

Upvotes: 4

Related Questions