Fiendcoder1
Fiendcoder1

Reputation: 119

Adding back codes to hyperlink in asp

I have first this

<li><asp:HyperLink id="logoutBtn" NavigateUrl="login.aspx" Text="Logout" runat="server"><i class="fa fa-sign-out fa-fw"></i> Logout </asp:HyperLink></li>

But I think it goes first to the page before he runs the back code which is this.

public void logoutBtn_Click(object sender, EventArgs e)
{
    Session.Clear();
    Response.Redirect("../login.aspx");
}

So basically I can still access any site because the Session is not cleared.

How can I achieve that whenever I click the HyperLink the code is fired?

Upvotes: 0

Views: 86

Answers (1)

Marco
Marco

Reputation: 23945

The purpose of a hyperlink is to navigate the user to another destination. (Plus, you don't have a click eventhandler attached to you hyper link, that will run your code behind.)

If you want to run server-side code use a good old button:

<asp:Button ID="logoutBtn" runat="server" onclick="logoutBtn_Click" Text="Logout" />  

public void logoutBtn_Click(object sender, EventArgs e)
{
    Session.Clear();
    Response.Redirect("../login.aspx");
}

If you want to use an asp:Hyperlink control to logout the user, navigate him to a specific logout page:

<li><asp:HyperLink id="logoutBtn" NavigateUrl="logout.aspx" Text="Logout" runat="server"><i class="fa fa-sign-out fa-fw"></i> Logout </asp:HyperLink></li>

Create the logout.aspx page and in the Page_Load event, log the user out:

protected void Page_Load(object sender, EventArgs e)
{
    Session.Clear();
    Response.Redirect("../login.aspx");
}

Upvotes: 1

Related Questions