Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose Header in ASP.NET Page

I have created a master page (Site.master) which contains the code to display a header, a footer, and a side bar. It works really great, but I am having trouble figuring out how to dynamically choose the header.

Basically, there are two possible header options. If the user is not logged in, I want them to see a login box and links for recovering their password, etc. If they are logged in, they'll see a logout link, and some information about their account (similar to how SO works, actually).

Is it possible to have the Site.master check and use whichever header I want depending on the login status of the user? I'm pretty stuck on where to begin with this (I thought maybe some checks in the code-behind of the master page) so any help would be appreciated.

like image 742
JasCav Avatar asked Feb 11 '10 20:02

JasCav


2 Answers

You should consider using the built-in control, LoginView (MSDN). It is specifically designed to provide multiple templates (views), for authenticated and anonymous users.

This is a best practice approach. You can define your headers/footers etc. for logged in and anonymous users, with appropriate login/logout buttons, user information, etc. etc.

Here's a very basic example:

<asp:LoginView id="LoginView1" runat="server">
    <AnonymousTemplate>
        <asp:HyperLink ID="lnkLogin" runat="server" NavigateUrl="~/Login.aspx" Text="Login"/>
    </AnonymousTemplate>
    <LoggedInTemplate>
        You are logged in as: <asp:LoginName id="lnCurrentUser" runat="server" />.
    </LoggedInTemplate>
</asp:LoginView>

The .NET framework will handle the rest, and display the correct template without any extra code. If you end up using multiple roles in your application you can take this one step further and define templates for these roles as well (administrator vs regular user, etc.)

A perfect solution to your question based on the above: How to: Display Different Information to Anonymous and Logged In Users

like image 117
KP. Avatar answered Sep 30 '22 06:09

KP.


Yes, very easily by putting the two possible headers in their own Panel controls and just saying the following in the Page_Load:

if ( Request.IsAuthenticated )
{
    // Display
    pnlAuthenticated.Visible = true;
    pnlGuest.Visible = false;
} 
else 
{
    // Display
    pnlAuthenticated.Visible = false;
    pnlGuest.Visible = true;
}
like image 43
Keith Adler Avatar answered Sep 30 '22 08:09

Keith Adler