I was refactoring some old website the other day and stumbled upon this scenario. I have an ASP.NET 3.5 C# WebForms page. In the code behind I have an event handler like so:
protected override void OnPreRender(EventArgs e) { }
On the other hand, in the markup, I also have:
<script language="C#" runat="server">
void Page_PreRender()
{
}
</script>
Question is: what does the lifecycle look like? What is executed first? Is one of them even executed?
When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering.
ASP.NET Page Life Cycle includes events PreInit, Init, InitComplete, OnPreLoad, Load, PostBack, LoadComplete, OnPreRender, OnSaveStateComplete, Render, and UnLoad.
The Asp.net page life cycle includes the events preinit, Init, InitComplete, OnPreLoad, Load, LoadComplete, OnPreRender, and OnSaveStateComplete. These events take place whenever an ASP.NET page is requested.
Two points upfront:
OnPreRender
method is not an event handler. It is an override of the method Page.OnPreRender
(which is the method that will raise the PreRender
event).Page_PreRender
is automatically wired-up to the PreRender
event. So this is an event handler (for the PreRender
event).Order of invocation
The following code sample shows the order of execution:
// code-behind
protected override void OnPreRender(EventArgs e)
{
// 1. code put here will be executed first
// now we call the base class' version, which will then raise the
// PreRender event
base.OnPreRender(e);
// 3. code put here will be executed last
}
// markup
<script language="C#" runat="server">
void Page_PreRender()
{
// 2. code put here will be executed second
}
</script>
Note that inside OnPreRender()
the base class is invoked: base.OnPreRender()
. As written above, if this is missing then the PreRender
event will not be raised and event handlers will therefore not be called.
Your code sample
In your sample code, the call to base.OnPreRender
is missing. This means, that PreRender
event is not raised and therefore the (event handler) method Page_PreRender()
will not be called.
Some more points to consider
If you have a Page_PreRender()
event handler in your markup and in your code-behind, then only the one in the code-behind will be called.
If you disable the auto-wiring of events in the Page directive (e.g. < % @ Page AutoEventWireup="false" ... % >
), then the Page_PreRender()
event handler will not be wired/connected with the PreRender
event and will therefore not be called.
You can also manually attach handlers to events, e.g:
protected void Page_Load(object sender, EventArgs e)
{
PreRender += PreRenderEventHandler;
}
void PreRenderEventHandler(object sender, EventArgs e)
{
}
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