views:

71

answers:

2

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?

+1  A: 

Use something like this:

<% if(Roles.IsUserInRole("Administrator")){ %>
<span>HTML Code</span>
<% } %>
Paul
Opps, sorry it's C#, but the idea would be the same...
Paul
Perfect, thanks!
Duk
You may want to think about long term maintainability with this approach. I would rather see the Model for the view have a flag CanSeeAdminSecrets and set that flag from the controller using the Roles.IsUserInRole method. The definition of an Admin could change in the system at a later point and having the logic for what an admin is in the controller makes more sense. Thought it's just preference really.
Jab
If you are going to go through that, it would be better to place such code in an extention method of the Roles class--adding it to the model just moves the definition from a number of views to about the same number of controller actions--if it were in an extension method the definition would be in one spot.
Paul
A: 

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

bearing09