Search code examples
c#asp.netwebformsanchorascx

Inline C# code should be run only when clicked ASP.NET


  <a href='MainPage.aspx<%=Session["IDs"] = null%>'>Log out</a>

The above code is written in Navigation.ascx(Web Form User Control), and navigation is registered in almost all website pages. Now i want above code <%=Session["IDs"] = null%> to run only when i click on log-out.

Rite Now when i navigate to any page the above code runs every time. I am navigating through anchor tag.

**NEW CODE

<a runat="server" id="alogout" onclick="logout_click" href="#">Log out</a>

protected void logout_click(object sender, EventArgs e) { Session["IDs"] = null; Response.Redirect("Login.aspx"); }


Solution

  • You have several options:

    1. Add ID for the :

      <'a runat="server" id="my_anchor" href='MainPage.aspx' onclick="anchor_click">Log out</a>
      

      then add a method on the code behind:

      protected void anchor_click(object sender, EventArgs e)
      {
          Session["IDs"] = null;
      }
      
    2. Change the href to another page that has Session["IDs"] = null and redirect to MainPage.aspx: <a href='RedirectToMainPage.aspx'>Log out</a>