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.
Related
I'm adding dynamic controls to a page based on data from a database to generate RadioButtonList questions.
Sometimes the questions are required, in which case after the data is retrieved from the database and the RadioButtonList is populated, I dynamically add a RequiredFieldValidator for the RadioButtonList.
The problem arises on postback, when in Page_Load() I execute Page.Validate() which always fails. I discovered that this is because the controls are being re-added on post-back but they aren't repopulated with the user's responses.
My question is:
When can I grab the user's response once they click "Submit", where do I store it, and what's the best way to bring it back so that Page.Validate() validates against controls with the proper responses?
Instead of creating the validation controls in Page_Load (or in a function that's called from within page_Load) do so in Page_Init
For more info see the Page Lifecycle:
In the Page Lifecycle, putting it in Page_Init allows the controls to be created on each page load, but BEFORE the viewstate values are applied. This means that the controls are created, and then the user selection is applied.
If you have it in Page_Load, then the controls are created AFTER the Viewstate values are applied. This means that the controls are just created from scratch after the viewstate has been applied, resetting everything to the default value.
Actually, this page says it better:
During page initialization, controls on the page are available and
each control's UniqueID property is set. Any themes are also applied
to the page. 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.
During load, if the current
request is a postback, control properties are loaded with information
recovered from view state and control state.
Use Page_Init when you
have to create controls dynamically. The controls are created every
time that the page is run. The best place to do this is in the
Page_Init function.
I use LoadControl method in Load event quite extensively. However I haven’t observed any problems yet, I’m afraid of what MSDN documentation says:
When you load a control into a container control, the container
raises all of the added control's events until it has caught up to the
current event. However, the added control does not catch up with
postback data processing. For an added control to participate in
postback data processing, including validation, the control must be
added in the Init event rather than in the Load event.
What does it actually mean?
Are there any other pitfalls when loading a control in the Load event?
That bit of MSDN documentation is (mostly) wrong. As you've discovered, postback data processing and validation work even if you dynamically add controls in the Load event.
Here are the stages of the ASP.NET page life cycle that are relevant to this question:
Raise the Init event.
Postbacks: Load view state and control state.
Postbacks: Load posted form data (first attempt).
Raise the Load event.
Postbacks: Load posted form data (second attempt).
Postbacks: Validate the form and raise the postback event.
The documentation is correct when it says that "the added control does not catch up with postback data processing". But it overlooks the fact that there are two attempts to load posted form data, once before the Load event and once after. Thus, if you dynamically add a control in the Load event, it will be populated with posted form data by the time the postback event (such as submitButton_Click) occurs.
As far as I can tell, here's the main difference and potential pitfall:
If you dynamically add a control in Init, you can access its posted form data in Load.
If you dynamically add a control in Load, you have to wait until the postback event (or else access the HttpRequest.Form collection directly).
It means that by the time Control_Load executes, the postback cycle has come and gone. If you have a control that needs to participate in postback, you need to load it before, so that's why the docs recommend doing it in the Init override instead.
If your controls don't participate in postback then you're OK.
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."
From the ASP.Net Page Lifecycle article on MSDN:
Although both Init and Load recursively occur on each control, they happen in reverse order. The Init event (and also the Unload event) for each child control occur before the corresponding event is raised for its container (bottom-up). However the Load event for a container occurs before the Load events for its child controls (top-down).
This makes a lot of sense for the unload event, but why for init? What about the other events?
Kind regards,
This is due to how these pages are created - the user controls are properties of the page's class. They are created (and hence initialised) as the class is initialised, which ensures that their instances are available during the constructor and page's init event.
Then when load, prerender and render events occur the page's event fires first and cascades the events for everything inside it.
When the unload and dispose come around the property objects are dealt with first again.
The WebForm page event model is a little too complicated, IMHO.
We have created a control that needs to persist data via the ViewState property of the Control class. Our class subclasses control strictly to get access to the ViewState property (it's protected on the Page object). We are adding the control to Page.Controls in OnInit, and then attempt to set the ViewState property in OnPreLoad.
When we decode and examine the ViewState of the page, our values have not been written out, and are thus not available for later retrieval.
Does anyone know how we can get our control to participate in the ViewState process?
The issue is adding the control to the Page directly. Unfortunately this is too high up the controls hierarchy to participate in the Forms ViewState Handling. If you add the control onto the actual ASPNet Form's Controls collection somewhere then it will successfully participate in LoadViewStateRecursive and SaveViewStateRecursive.
Try creating your control in OnInit, then add it to the Page.Controls during OnLoad.
ViewState isn't loaded until after OnInit, but before OnLoad.
Here's a rough outline of the Page Life-Cycle(GregMac) posted this in a response to an earlier question of mine.
Initialize
LoadViewState
Load Postback Data
Call control Load events
Call Load event
Call control events
Control PreRender
PreRender
SaveViewState
Unload