0

I want to display an Admin ActionLink on my homepage if a user's role is 'Admin'. I have managed to get the roles configured correctly but I'm unsure how to do it.

So far I have implemented the following code into my HomeController:

        Function Admin() As ActionResult
        If Roles.IsUserInRole("Admin") Then
            Return View("Admin")
        Else
            Return View()
        End If
        End Function 

I have then implemented the following ActionLink into my Site.Master:

<li><%: Html.ActionLink("Admin", "Admin", New With {.Controller = "Home"})%></li>

I know this isn't correct but it's not something I've done before so I'm not too sure how it can be implemented correctly.

Thanks for any help.

2 Answers2

1

You write this code inside your view using razor, something like this:

Razor

@If User.IsInRole("Admin") Then
   <li>@Html.ActionLink("Admin", "Admin", New With {.Controller = "Home"})</li>
End if

ASPX

<% If User.IsInRole("Admin") Then %>
   <li><%: Html.ActionLink("Admin", "Admin", New With {.Controller = "Home"})%></li> 
<% End if %>
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
0

i am not familiar with VB.NET But you can do it by writing a custom Helper function as below:

 public static MvcHtmlString If(this MvcHtmlString value, bool evaluation)
    {
         return evaluation ? value : MvcHtmlString.Empty;
    }

so you can use this:

 @Html.ActionLink("Admin", "Admin").If(User.IsInRole("Administrator"))
Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79
  • Thanks. Excuse my ignorance but I have never used custom helpers before. Where do I implement two sections? –  Mar 12 '13 at 16:56
  • @David As you see, custom helper is nothing but an extension method , so you will need to put it anywhere but in a static class (`HelperExtensions` may be)...and you can use it on any view page by just importing the namespace in which the static class is put... – Bhushan Firake Mar 12 '13 at 16:58