Monday, April 27, 2009

Magic of Page Load and Page Init execution

Problem:
Lack of knowledge in understanding the complete Page Life Cycle in ASP.NET.

This is very helpful in big projects. Take the below scenario.
We need to initialize an object in Master page page load event and try to access the same object in aspx page load event. But this will throw an error because aspx page load always executes first than master page page load event. Yes, it is. This is the issue by many developers as they don't understand the life cycle correct. The correct way should be, initiating the object in page init event of the master page and aspx pages.

Scenario I,
If we have a page called "Default" and a Master page called "DefaultMaster". Both have Page_Load events. When a page request comes to Default page, which Page Load event will call first?
Answer: default.aspx page load.

Scenario II,
The same pages as above with Page_Init event is also available along with Page_Load. Now which Page_Init will call first by .net run time?
Answer: Master page init event, but not default.aspx page init event.

This is the good point to know that, All page Init events will process from master page to aspx pages and all page Load events will process from aspx pages to master pages.

Page Init EventPage Load event
1. Execution sequence starts from Init event of Main master page--> Sub Master Page --> ……. -->Requested ASPX page init event.1. Execution sequence starts from Load event of Requested ASPX page --> Sub Master Page --> ……. --> Main master page load event.

Whole Page Life Cycle which contains both events should be executed as below:
Master page Init --> Sub Master Page Init --> …. --> ASPX Init --> ASPX Load--> …. --> Sub Master Page Load --> Master page Load.

3 comments:

  1. Good... worth to note

    ReplyDelete
  2. Thanks there. I have changed the format of the post to more readable way. Thanks for the wonderful comment!

    ReplyDelete