I have a button that calls function A()
When I click on it I want the calls to be made in that order:
A()
Page_Load()
Right now it's doing:
Page_Load()
A()
Is there a way around that or is it just by design and there's nothing I can do about it?
The easiest way to do this would be to use a HTML Submit button and check to see if it is in the Form on every postback in Page_Init
public void Page_Init(object o, EventArgs e)
{
if(!string.IsNullOrEmpty(Request.Form["MyButtonName"]))
{
A();
}
}
And in your ASP.NET code:
<Button Type="Submit" Name="MyButtonName" Value="Press Here To Do Stuff Early!" />
I think that will work.
Control events (such as the click events of buttons) are called after page_load. The controls are not guarenteed to be fully initialized prior to page_load. If you really need to call a function before page_load has been called based on whether a button has been pressed you'll have to examine the request to check if the button has been pressed (basically old school ASP)
You need to call your function in the Page_Init. Page_Init will happen before Page_Load.
Here's an Overview of the ASP.NET Page Lifecycle.
Not exactly: ASP.NET will always call Page_Load
before handling postback events like Button_Click
.
However, you can accomplish what you want by redirecting to your page after handling the postback event. (Using the Post-Redirect-Get pattern.)
Inside your Page_Load method, you can avoid running any relevant code twice by checking to see if it's a postback first:
if (!this.IsPostBack) {
// Do something resource-intensive that you only want to do on GETs
}
As Jeff Sternal answered, The Post-Redirect-Get pattern is a good way of solving a problem like this.
In my circumstances i had a calendar and if you clicked a date it would add that to a scheduler. The scheduler would have buttons on each new date that needed to have onclick functions tied to them.
Because the new row was being added with a linkbutton(on the calendar), in the code the new scheduler date was being added at the Postback event handling meaning that the new set of buttons wouldn't have a command tied to them.
The page life Cycle
Post Get Redirect
I don't think it's possible, at least, not in the way described by your question. When you click a button it will send a request to the server which in turn will start processing it, and follow the ASP.NET Page Lifecycle as posted by Joseph.
Alternatively you could try making an AJAX call to a page without reloading the current one you're on and do whatever processing you require.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With