Sunday, April 19, 2020

Page Life Cycle In ASP.NET

Let's learn ASP.Net page life cycle and how different events are fired during an ASP.NET page life cycle. 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. The following are the various stages or events of ASP.Net page life cycle.
 
ASP.NET Page Life Cycle 
 

PreInit

  1. Check the IsPostBack property to determine whether this is the first time the page is being processed.
  2. Create or re-create dynamic controls.
  3. Set a master page dynamically.
  4. Set the Theme property dynamically.

    Page Life Cycle In ASP.NET
Note
 
If the request is a postback then the values of the controls have not yet been restored from the view state. If you set a control property at this stage, its value might be overwritten in the next event.
 

Init

  1. This event fires after each control has been initialized.
  2. Each control's UniqueID is set and any skin settings have been applied.
  3. Use this event to read or initialize control properties.
  4. The "Init" event is fired first for the bottom-most control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.

    Page Life Cycle In ASP.NET

InitComplete

  1. Until now the viewstate values are not yet loaded, hence you can use this event to make changes to the view state that you want to ensure are persisted after the next postback.
  2. Raised by the Page object.
  3. Use this event for processing tasks that require all initialization to be complete.

    Page Life Cycle In ASP.NET

OnPreLoad

  1. 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.
  2. 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.
  3. Loads ViewState: ViewState data are loaded to controls.
  4. Loads Postback data: Postback data are now handed to the page controls.

    Page Life Cycle In ASP.NET

Load

  1. 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.
  2. This is the first place in the page lifecycle that all values are restored.
  3. Most code checks the value of IsPostBack to avoid unnecessarily resetting state.
  4. You may also call Validate and check the value of IsValid in this method.
  5. You can also create dynamic controls in this method.
  6. Use the OnLoad event method to set properties in controls and establish database connections.

    Page Life Cycle In ASP.NET

Control PostBack Event(s)

  1. ASP.NET now calls any events on the page or its controls that caused the PostBack to occur.
  2. Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
  3. 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.
  4. This is just an example of a control event. Here it is the button click event that caused the postback.

    Page Life Cycle In ASP.NET

LoadComplete

  1. Raised at the end of the event-handling stage.
  2. Use this event for tasks that require that all other controls on the page be loaded.

    Page Life Cycle In ASP.NET

OnPreRender

  1. Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls.
  2. 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.
  3. The PreRender event of individual controls occurs after the PreRender event of the page.
  4. Allows final changes to the page or its control.
  5. This event takes place before saving ViewState, so any changes made here are saved.
  6. For example: After this event, you cannot change any property of a button or change any viewstate value.
  7. Each data bound control whose DataSourceID property is set calls its DataBind method.
  8. Use the event to make final changes to the contents of the page or its controls.

    ASP.NET7.5.jpg

OnSaveStateComplete

  1. Raised after view state and control state have been saved for the page and for all controls.
  2. Before this event occurs, ViewState has been saved for the page and for all controls.
  3. Any changes to the page or controls at this point will be ignored.
  4. Use this event perform tasks that require the view state to be saved, but that do not make any changes to controls.

    Page Life Cycle In ASP.NET

Render Method

  1. This is a method of the page object and its controls (and not an event).
  2. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

UnLoad

  1. This event is used for cleanup code.
  2. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object.
  3. Cleanup can be performed on:
    • Instances of classes, in other words objects
    • Closing opened files
    • Closing database connections.
  4. This event occurs for each control and then for the page.
  5. During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream.
  6. If you attempt to call a method such as the Response.Write method then the page will throw an exception.

    Page Life Cycle In ASP.NET

EXAMPLES

 
Example 1: Control Values
 
In the following code, I have assigned the values to the label control on each event. When you run the code, you will see that in the "Page_UnLoad", the values are not assigned to the label. WHY? Because, during the unload stage, the page and its controls have been rendered, so you cannot change the values.
 
Please observe the code comments and output. It will help you to clearly understand the concepts. 
  1. public partial class PageLiftCycle: System.Web.UI.Page {  
  2.     protected void Page_PreInit(object sender, EventArgs e) {  
  3.         //Work and It will assign the values to label.  
  4.         lblName.Text = lblName.Text + "<br/>" + "PreInit";  
  5.     }  
  6.     protected void Page_Init(object sender, EventArgs e) {  
  7.         //Work and It will assign the values to label.  
  8.         lblName.Text = lblName.Text + "<br/>" + "Init";  
  9.     }  
  10.     protected void Page_InitComplete(object sender, EventArgs e) {  
  11.         //Work and It will assign the values to label.  
  12.         lblName.Text = lblName.Text + "<br/>" + "InitComplete";  
  13.     }  
  14.     protected override void OnPreLoad(EventArgs e) {  
  15.         //Work and It will assign the values to label.  
  16.         //If the page is post back, then label contrl values will be loaded from view state.  
  17.         //E.g: If you string str = lblName.Text, then str will contain viewstate values.  
  18.         lblName.Text = lblName.Text + "<br/>" + "PreLoad";  
  19.     }  
  20.     protected void Page_Load(object sender, EventArgs e) {  
  21.         //Work and It will assign the values to label.  
  22.         lblName.Text = lblName.Text + "<br/>" + "Load";  
  23.     }  
  24.     protected void btnSubmit_Click(object sender, EventArgs e) {  
  25.         //Work and It will assign the values to label.  
  26.         lblName.Text = lblName.Text + "<br/>" + "btnSubmit_Click";  
  27.     }  
  28.     protected void Page_LoadComplete(object sender, EventArgs e) {  
  29.         //Work and It will assign the values to label.  
  30.         lblName.Text = lblName.Text + "<br/>" + "LoadComplete";  
  31.     }  
  32.     protected override void OnPreRender(EventArgs e) {  
  33.         //Work and It will assign the values to label.  
  34.         lblName.Text = lblName.Text + "<br/>" + "PreRender";  
  35.     }  
  36.     protected override void OnSaveStateComplete(EventArgs e) {  
  37.         //Work and It will assign the values to label.  
  38.         //But "SaveStateComplete" values will not be available during post back. i.e. View state.  
  39.         lblName.Text = lblName.Text + "<br/>" + "SaveStateComplete";  
  40.     }  
  41.     protected void Page_UnLoad(object sender, EventArgs e) {  
  42.         //Work and it will not effect label contrl, view stae and post back data.  
  43.         lblName.Text = lblName.Text + "<br/>" + "UnLoad";  
  44.     }  
  45. }   
Output
 
The first time the Page Load is output:
 
Page Life Cycle In ASP.NET 
 
When you click on the Submit Button output:
 
Page Life Cycle In ASP.NET 
 
During the first time of the page load with EnableViewState="false":
 
Page Life Cycle In ASP.NET 
 
When you click on the Submit Button output with EnableViewState="false":
 
Page Life Cycle In ASP.NET 
 
Example 2 ViewState Values
 
Please observe the code comments and output. It will help you to clearly understand the concepts. 
  1. public partial class PageLiftCycle: System.Web.UI.Page {  
  2.     protected void Page_PreInit(object sender, EventArgs e) {  
  3.         //Work and It will assign the values to label.  
  4.         //Note : If page is post back or first time call and you have not set any values to ViewState["value"], then  
  5.         //Convert.ToString(ViewState["value"]) is always empty.  
  6.         ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "PreInit";  
  7.         lblName.Text = Convert.ToString(ViewState["value"]);  
  8.     }  
  9.     protected void Page_Init(object sender, EventArgs e) {  
  10.         //Work and It will assign the values to label.  
  11.         //Note : If page is post back or first time call and you have not set any values to ViewState["value"] in privious events, then  
  12.         //Convert.ToString(ViewState["value"]) is always empty.  
  13.         ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "Init";  
  14.         lblName.Text = Convert.ToString(ViewState["value"]);  
  15.     }  
  16.     protected void Page_InitComplete(object sender, EventArgs e) {  
  17.         //Work and It will assign the values to label.  
  18.         //Note : If page is post back or first time call and you have not set any values to ViewState["value"] in privious events, then  
  19.         //Convert.ToString(ViewState["value"]) is always empty.  
  20.         ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "InitComplete";  
  21.         lblName.Text = Convert.ToString(ViewState["value"]);  
  22.     }  
  23.     protected override void OnPreLoad(EventArgs e) {  
  24.         //Work and It will assign the values to label.  
  25.         //Note : If page is post back and you have set or not set any values to ViewState["value"] in privious events, then  
  26.         //Convert.ToString(ViewState["value"]) will always have post back data.  
  27.         //E.g: If you string str = Convert.ToString(ViewState["value"]), then str will contain post back values.  
  28.         ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "PreLoad";  
  29.         lblName.Text = Convert.ToString(ViewState["value"]);  
  30.     }  
  31.     protected void Page_Load(object sender, EventArgs e) {  
  32.         //Work and It will assign the values to label.  
  33.         ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "Load";  
  34.         lblName.Text = Convert.ToString(ViewState["value"]);  
  35.     }  
  36.     protected void btnSubmit_Click(object sender, EventArgs e) {  
  37.         //Work and It will assign the values to label.  
  38.         ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "btnSubmit_Click";  
  39.         lblName.Text = Convert.ToString(ViewState["value"]);  
  40.     }  
  41.     protected void Page_LoadComplete(object sender, EventArgs e) {  
  42.         //Work and It will assign the values to label.  
  43.         ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "LoadComplete";  
  44.         lblName.Text = Convert.ToString(ViewState["value"]);  
  45.     }  
  46.     protected override void OnPreRender(EventArgs e) {  
  47.         //Work and It will assign the values to label.  
  48.         ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "PreRender";  
  49.         lblName.Text = Convert.ToString(ViewState["value"]);  
  50.     }  
  51.     protected override void OnSaveStateComplete(EventArgs e) {  
  52.         //Work and It will assign the values to label.  
  53.         //But "SaveStateComplete" values will not be available during post back. i.e. View state.  
  54.         ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "SaveStateComplete";  
  55.         lblName.Text = Convert.ToString(ViewState["value"]);  
  56.     }  
  57.     protected void Page_UnLoad(object sender, EventArgs e) {  
  58.         //Work and it will not effect label contrl values, view state and post back data.  
  59.         ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "UnLoad";  
  60.         lblName.Text = Convert.ToString(ViewState["value"]);  
  61.     }  
  62. }  
Output
 
During the first the Time Page Load is output:
 
Page Life Cycle In ASP.NET 
 
When you click on the Submit Button output:
 
Page Life Cycle In ASP.NET 
 
During the first time the page loads with EnableViewState="false":
 
Page Life Cycle In ASP.NET 
 
When you click on the Submit Button the output with EnableViewState="false":
 
Page Life Cycle In ASP.NET 
 
Example 3 ViewState Values
 
Please observe the code comments and output. It will help you to clearly understand the concepts. 
  1. public partial class PageLiftCycle: System.Web.UI.Page {  
  2.     protected void Page_PreInit(object sender, EventArgs e) {  
  3.         Response.Write("<br/>" + "PreInit");  
  4.     }  
  5.     protected void Page_Init(object sender, EventArgs e) {  
  6.         Response.Write("<br/>" + "Init");  
  7.     }  
  8.     protected void Page_InitComplete(object sender, EventArgs e) {  
  9.         Response.Write("<br/>" + "InitComplete");  
  10.     }  
  11.     protected override void OnPreLoad(EventArgs e) {  
  12.         Response.Write("<br/>" + "PreLoad");  
  13.     }  
  14.     protected void Page_Load(object sender, EventArgs e) {  
  15.         Response.Write("<br/>" + "Load");  
  16.     }  
  17.     protected void Page_LoadComplete(object sender, EventArgs e) {  
  18.         Response.Write("<br/>" + "LoadComplete");  
  19.     }  
  20.     protected override void OnPreRender(EventArgs e) {  
  21.         Response.Write("<br/>" + "PreRender");  
  22.     }  
  23.     protected override void OnSaveStateComplete(EventArgs e) {  
  24.         Response.Write("<br/>" + "SaveStateComplete");  
  25.     }  
  26.     protected void Page_UnLoad(object sender, EventArgs e) {  
  27.         //Runtime Error : Response is not available in this context.  
  28.         //Response.Write("<br/>" + "UnLoad"); //Error  
  29.     }  
  30. }  
Output
 
Page Life Cycle In ASP.NET 
 
Note: If you write Response.Write("<br/>" + "UnLoad"); in the Page_UnLoad event, then it will genenrate the Runtime Error "Response is not available in this context".
 
Page Life Cycle In ASP.NET 
 

No comments:

Post a Comment