Similar to LoginView from WebForms in Asp.Net Core Razor Pages

169 Views Asked by At

I have been searching but couldn't find anything about login view in razor pages. I liked login views and how easy it was to separate templates based on roles. Is there a way to do this in razor pages?

Here's LoginView from webforms example

<asp:LoginView runat="server">
    <RoleGroups>
        <asp:RoleGroups Roles="Admin">    
            <ContentTemplate>            
                Welcome Admin

            </ContentTemplate>
        </asp:RoleGroups>
        <asp:RoleGroups Roles="User">    
            <ContentTemplate> 
                Welcome User     

            </ContentTemplate>            
        </asp:RoleGroups>
    </RoleGroups>
</asp:LoginView>

Basically how to render different html for users based on their Roles

1

There are 1 best solutions below

1
Chris Pratt On BEST ANSWER

In general, in your views, you can use User.IsInRole:

@if (User.IsInRole("Admin"))
{
    @:Welcome Admin
}

@if (User.IsInRole("User"))
{
    @:Welcome User
}

Now, in terms of creating a reusable view, you either want to use a partial view or a view component. For this particular scenario, a partial view should be sufficient. View components are more appropriate when you need to inject dependencies, do custom queries or other advanced logic, none of which is necessary here.

So, create a new Razor view like _Login.cshtml and place your code there. Then, where you want to display that content, such as in a layout:

<partial name="_Login" />