imin
imin

Reputation: 4578

asp.net keeps on calling a function in page_load

I've a form (mainpage.aspx), on which there's a button called 'Cancel'. Here's the code for the button:

<asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" CssClass="btn btn-default" OnClick="btnCancel_Click" />

and the called function

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

So as you can see, what the button do is simple. Just go to another page. But it seems here that doesn't happen. Every time I click the Cancel button, first it will try to load the code

Response.Redirect("EventList.aspx");

but then somehow it will try to execute the codes below:

if (hdnEventId.Value != "" && hdnEventId.Value != "0")
            {
                LoadEvent();
}

I know this because I put a breakpoint on Response.Redirect("EventList.aspx"); and after that I step into the code above

btw the codes above are located inside

protected void Page_Load(object sender, EventArgs e)

inside the file mainpage.aspx.cs

Upvotes: 1

Views: 770

Answers (1)

Mathew Thompson
Mathew Thompson

Reputation: 56429

That's because Page_Load is called on any postback and you're actually doing a postback by clicking Cancel. The solution is to wrap your non-postback specific code in a IsPostBack check:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (hdnEventId.Value != "" && hdnEventId.Value != "0")
        {
            LoadEvent();
        }
    }
}

Upvotes: 1

Related Questions