Purpose of different order of execution: Init() and Load() - asp.net

During a recent interview the following question was asked.
• A Master page which contains
• An ASPX web form page which contains
• A Web User Control inside the page which contains
• A button to fire some code in a button_click event
The Init Event will fire (Inner Most to Outer Most)
aspx.page Begin Init
–> Inside user control Page_Init
–> Inside master page Page_Init
–> Inside lifecycle page Page_Init
aspx.page End Init
and Load Event will fire
aspx.page Begin Load
–> Inside lifecycle page Page_Load
–> Inside master page Page_Load
–> Inside user control Page_Load
aspx.page End Load
Why does ASP.NET framework support different execution order in Load() and Init().This was the question asked in interview.I have no idea about what the interviewer expecting from me.
I request your help please.

I suggest reading about the ASP.NET page life cycle.
The two have different purposes, hence different execution order.
Initialization :
During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
Load:
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.
Additionally, you need to understand the relationship between master pages and content pages (master pages are in fact included in the content pages, not the other way around) and the complete life cycle of both.
So, during init, the user controls need to be initialized first, so they are available to their container, then the master page so it's contents are available to the content page and then the page itself, completing the control hierarchy initialization.
During load, the opposite happens, as now all postback data has been set and all the controls are ready and can fire their different events. The top container, the content page loads first (as it can change the master page and user controls), then the master page and in the end the leaf controls.

The reason is for control management. Sometimes you need to create controls dynamically and in order for them to work correctly, you need to re-create them on the init and not the onload(). If you don't re-create the controls onInit, you're dynamic controls will not working properly.

Related

What is the order of events execution in Asp.Net

Can anyone please tell me the order of events execution in Asp.Net
Taken from http://msdn.microsoft.com/en-us/library/vstudio/ms178472(v=vs.100).aspx
PreInit
Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Read or set profile property values.
NoteNote If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.
Init
Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.
Use this event to read or initialize control properties.
InitComplete
Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.
Use this event to make changes to view state that you want to make sure are persisted after the next postback.
PreLoad
Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.
Load
The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.
Use the OnLoad event method to set properties in controls and to establish database connections.
Control events
Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
Note In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
LoadComplete
Raised at the end of the event-handling stage.
Use this event for tasks that require that all other controls on the page be loaded.
PreRender
Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)
The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.
Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.
PreRenderComplete
Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.
SaveStateComplete
Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
Render
This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser.
If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.
A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.
Unload
Raised for each control and then for the page.
In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.
For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.
Note During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Why Unload event of masterpage calls before unload of aspx page?

i was trying to find the sequence of event between Master page and aspx page.
I came to know that unload event of master page calls before then unload event of ASPX page.
I already read this in many websites but i am looking for reason behind it.
If someone has an idea about this then kindly help me.
One good reason I found is this::
Master pages behave like child controls on a page.
What this means is that the way any Control events are raised by the Asp.Net page life cycle, same way it will raise events for Master pages.
Consider for example, the Init event. MSDN says that the Init event of individual controls occurs before the Init event of the page. And thus, the Init event of Master page occurs before the Init event of page.
One more example, consider the Load event.MSDN says that the Load event of individual controls occurs after the Load event of the page. Therefore the Load event of Master page occurs after the load event of content page.
This is indeed confirmed by MSDN::
Master pages behave like child controls on a page: the master page Init event
occurs before the page Init and Load events, and the master page Load event
occurs after the page Init and Load events
So, now you can say that the way Unload event is raised for controls, it will be same for master page.
The Unload event is raised for each control first and then for the page. So this is the reason why Unload event of master page is called before Content page.

why is a page_load significant in aspx.cs?

Can someone explain to me the sheer purpose of a page load? My code runs just fine without it right now in my aspx.cs (codebehind) file. I am doing very basic stuff here, so im guessing it has a lot of importance somewhere so i am just wondering what that would be. thanks for any help!
You should check about the Page Life Cycle.
The load is an event in this Cycle.
About the method, Page_load() is the method on the server side application, for an .aspx file. All code inside of this method is executed once at the beginning of the page.
Also, in the load, if the current request is a postback, control properties are loaded with information recovered from view state and control state. (Different from initialize, when you set the default values)
So, in the Load Event, the Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.
Some links for you:
ASP .NET Page Life Cycle
Page_Load and Postback
and there are a few more in Google

Dynamically created controls are wiped out on button click

I have webform where a set of controls are generated in a Panel control during a SelectedIndexChanged event of a dropdown. That all works fine.
However, when I enter values in those controls and I click on my submit button, the controls are wiped out along with the data I entered.
I can only create the controls in that SelectedIndexChanged event because that's where I get the info to generate the dynamic controls.
What I'd like to do is keep those controls displayed with the data I entered and use the data I entered to do something else (like it happens in WinForms.)
Is this doable?
Thanks!
Every time a postback occurs you are working with a new instance of your page class. Dynamic controls added to the page during a previous postback went to the garbage collector as soon as the page for that postback rendered to the browser. You need to re-create your dynamic controls on every postback.
Save the count of "control-sets" in Session or ViewState, so that you can regenerate them with their appropriate ID's(f.e. appendeded with an indexOfControl) during Page_Init.
Here are some additional informations on:
View State and Dynamically Added Controls *
ASP.NET Page Life Cycle Overview
Extract:
Dynamically added controls must be programmatically added to the Web page on each and every page visit. The best time to add these controls is during the initialization stage of the page life cycle, which occurs before the load view state stage. That is, we want to have the control hierarchy complete before the load view state stage arrives. For this reason, it is best to create an event handler for the Page class's Init event in your code-behind class, and add your dynamic controls there.
This is one of those areas where the attempt to make Webforms look like Winforms fails.
With Webforms, you need to do the whole dance of when to create controls. I believe all your controls will need to be recreated by some time around the end of PageLoad. There might be an event or two after page load that you can use, but generally speaking PageLoad is a safe time to create controls.
Essentially the controls need to be created before ASP.NET populates them with data from ViewState/Browser.

ASP.NET: Viewstate and programmatically adding user controls

When programmatically adding user controls using LoadControl(string path), when, in the user control's page life cycle, does it initialize its sub-controls with its viewstate?
I'm asking this question because one of my user controls that's being programmatically loaded has a TextBox control that is not being initialized/loaded by it's viewstate on PostBack on the Page_Load event (which is not the case for a regular .aspx pages and hence my confusion). Overall, I need to retrieve values from the Textbox control.
Thanks
ViewState is loaded before the Page_Load event. If you want your control to work with ViewState, you need to load it and add it to the page before that event — usually on PreInit.
The life cycle reference is here:
http://msdn.microsoft.com/en-us/library/ms178472.aspx?ppud=4
Read the description for the Pre Load event, which immediately precedes Page Load:
Use this event if you need to perform processing on your page or control before the Load event.
Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.
Thus by Pre Load time it's already too late. Also, the description for the PreInit event specifically mentions that it's the place to "create or re-create dynamic controls."

Resources