I have a menu item “Login” that navigates to the login page. When a user is logged in, I have the text for that menu item changing to “Logout”. When clicked, I want it to go back to clear the session, go to the login page, and for the text to change back to “Login”. And this works…kinda. The problem I’m having is that I don’t know how to call a function when clicking on a menu item, so when the user clicks “Logout” the login page loads and the session is cleared when the page loads, but since it’s not cleared before the page loads, it still appears that there is a session (username still appears, and menu item text isn’t changed). How can I set it so that the session is cleared in “Logout” is clicked instead of when the login page loads?
Here’s my menu code:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="LeftSideMenu.ascx.cs" Inherits="EVMAnywhereWeb.Controls.LeftSideMenu" %>
<div id="leftSideMenu">
<asp:menu ID="menu1" runat="server" Orientation="Vertical" RenderingMode="List">
<StaticMenuItemStyle VerticalPadding="5" />
<DynamicMenuItemStyle VerticalPadding="5" />
<Items>
<asp:menuitem navigateurl="~/Login.aspx" Text="Login" Value="Login"></asp:menuitem>
<asp:menuitem navigateurl="~/Register.aspx" Text="Register" Value="Register"></asp:menuitem>
<asp:menuitem navigateurl="~/Projects.aspx" Text="Projects" Value="Projects"></asp:menuitem>
<asp:menuitem navigateurl="~/Dictionary.aspx" Text="Dictionary" Value="Dictionary"></asp:menuitem>
</Items>
</asp:menu>
</div>
Here’s the code I use to change the text (in the code-behind):
protected void Page_Load(object sender, EventArgs e)
{
if (Session["SessionUserName"] != null)
{
menu1.Items[0].Text = "Logout";
menu1.Items[1].Text = "My Account";
}
}
And in the login page code-behind, I have this to clear the session:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["SessionUserName"] != null)
{
Session.Abandon();
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
}
}
Call your code to clear the session in OnInit instead of Page_Load.