How to use the LoginView Control with Roles in ASP.NET

You can use the LoginView control to display different controls for anonymous and logged-in users by using templates <AnonymousTemplate> and <LoggedInTemplate> which implement this functionality. You can find more information from the article How to use ASP.NET membership LoginView control.

C# in Depth, 3rd EditionManaged Windows VPS Hosting

The control supports one additional template that enables you to create different views based on the roles to which a user belongs. For this purpose you should:

1. Add a RoleGroups template with <asp:RoleGroup> controls.

2. Within every <asp:RoleGroup> control, you specify a comma-separated list of roles in the Roles attribute for which its <ContentTemplate> will be displayed.

 

The next example shows this approach:

 

<asp:LoginView ID=”LoginViewCtrl” runat=”server”>

<AnonymousTemplate>

<h2>You are anonymous</h2>

</AnonymousTemplate>

<LoggedInTemplate>

<h2>You are logged in</h2>

Submit your comment: <asp:TextBox runat=”server” ID=”CommentText” />

<br />

<asp:Button runat=”server” ID=”SubmitCommentAction” Text=”Submit” />

</LoggedInTemplate>

<RoleGroups>

<asp:RoleGroup Roles=”Admin”>

<ContentTemplate>

<h2>Only Admins will see this</h2>

</ContentTemplate>

</asp:RoleGroup>

<asp:RoleGroup Roles=”Supervisor“>

<ContentTemplate>

<h2>This is for Supervisors!</h2>

</ContentTemplate>

</asp:RoleGroup>

<asp:RoleGroup Roles=”Tester, Designer”>

<ContentTemplate>

<h2>This is for web designers and testers</h2>

</ContentTemplate>

</asp:RoleGroup>

</RoleGroups>

</asp:LoginView>