Search code examples
c#asp.net.netmaster-pages

Page_Load is called when leaving page


I have a master page and two web pages, WebForm1 and WebForm2. On the master page there are two LinkButtons in order to go to WebForm1 or WebForm2.

When I click on the LinkButton to go to WebForm1 the Page_Load event handler for WebForm1 is called and Page.IsPostBack == false. So far so good.

Then when I click to go to WebForm2 this happens:

a) The Page_Load event handler for WebForm1 is called again and Page.IsPostBack == true.
b) Then the Page_Load event handler for WebForm2 is called and its Page_Load == false.

Vice versa when going back to WebForm1.

Why is Page_Load for WebForm1 called when I'm going to WebForm2? I am loading WebForm2 and not WebForm1.

For all pages: AutoEventWireup="true".

<form id="form1" runat="server">
<div>
    <p>This is MySite.Master.</p>
    <p>
        <asp:LinkButton ID="goto1" runat="server" OnClick="goto1_Click">Go To WebForm1</asp:LinkButton>
    </p>
    <p>
        <asp:LinkButton ID="goto2" runat="server" OnClick="goto2_Click">Go To WebForm2</asp:LinkButton>
    </p>

    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
    </asp:ContentPlaceHolder>
</div>
</form>


protected void goto1_Click(object sender, EventArgs e) {
    Response.Redirect("WebForm1.aspx");
}

protected void goto2_Click(object sender, EventArgs e) {
    Response.Redirect("WebForm2.aspx");
}



public partial class WebForm1 : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {

        if (Page.IsPostBack) {

        }
    }
}



public partial class WebForm2 : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {

        if (Page.IsPostBack) {

        }
    }
}

Solution

  • To add on to Kirk's answer...

    When you just want a simple link to another page, don't use LinkButton at all. LinkButton is just a submit button, which is designed to look like a link - it's all hooked up magically through javascript that ASP.NET builds automatically.

    If you want a link to simply send you to another page, just do it in regular HTML:

    <a href="WebForm2.aspx">Go To WebForm2</a>