Controls based on roles or logged in

How do I wrap code around a user control in order to indicate that it should only be displayed if the user has a certain role?

Same also for only displaying if a user is logged in?

I know how to register one and put it on the page, I just don't know how to do the if/else stuff.


Starr DuskkASP.NET VB.NET DeveloperAsked:
Who is Participating?
CJ_SConnect With a Mentor Commented:
Well - you didn't copy the code as I gave you. Note the different quotation marks

Visible='<%# Page.User.IsInRole("administrator")%>'

Multiple roles:
Visible='<%# (Page.User.IsInRole("administrator") or Page.User.IsInRole("editor"))%>'

Not in a role (using C#)
Visible='<%# !Page.User.IsInRole("administrator")%>'

Not in a role (using VB.Net)
Visible='<%# Not Page.User.IsInRole("administrator")%>'

Two options imo.
1) use the provided control (asp:LoginView) and use the appropriate template
2) use a little bit of code (<asp:.... visible='<%# Page.User.IsAuthenticated%>' /> or <asp:.... visible='<%# Page.User.IsInRole("administrator")%>' />)

Starr DuskkASP.NET VB.NET DeveloperAuthor Commented:
when I use that on a control:
Visible="<%# Page.User.IsInRole("administrator")%>"

I get an error: Parser Error Message: The server tag is not well formed.

<uc:RBox ID="RBox1" runat="server" Visible="<%# Page.User.IsInRole("administrator")%>" />

Isn't there a way to do multiple roles?

Or if the user is NOT in the role?

The new generation of project management tools

With’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Starr DuskkASP.NET VB.NET DeveloperAuthor Commented:
great answer!
Starr DuskkASP.NET VB.NET DeveloperAuthor Commented:
Starr DuskkASP.NET VB.NET DeveloperAuthor Commented:
Ugh. I graded too soon.

<uc:BannerAdvfn ID="Banner1" runat="server" visible='<%# Page.User.IsAuthenticated%>'  />

gives this error:
Compiler Error Message: BC30456: 'IsAuthenticated' is not a member of  'System.Security.Principal.IPrincipal'.
My bad

'<%# Page.User.Identity.IsAuthenticated%>'
Starr DuskkASP.NET VB.NET DeveloperAuthor Commented:
Well, even that doesn't seem to work with single or double quotes (it says I have to have double to match the rest of my control), or NOT or not NOT. It always displays whether logged in or not:

<uc:MenuAd ID="Menu2" runat="server" Visible="<%# Page.User.Identity.IsAuthenticated%>"/>

But that's okay. Someone else showed me how to define it in the page load... which works better for my purposes anyway.


        If isLoggedIn Then ' defined above.....
            Me.Menu1.Visible = False
            Me.Menu2.Visible = False
        End If
All Courses

From novice to tech pro — start learning today.