Tuesday, 2 July 2013

Define page life cycle events with example in ASP .Net

Here You will get the solution of following queries:
Ques: What is page life cycle in asp .Net?
Ques: Describe events used in complete asp .net page life cycle.
Ques: Specify phase used in asp .Net page life cycle
Ques: Define Init, Load, Render and Unload events in page life cycle.


I L  R S U

I - Init
L-Load
R-Render
S-SaveState
U -Unload





Today I want to share some knowledge about ASP .Net. Every developer who is working on ASP .Net must know about the Page life cycle[first step of web development using .Net technology]. Some of our friends after having 2-3 years of ASP .Net experience still don't have proper knowledge about all the events used in Page Life Cycle . As a developer I always got confused about page life cycle events in my beginning days, Here I am describing all the events with examples wherever applicable.

PreInit 
PreInit is the first phase in asp.net page life cycle events. This is the place where one can dynamically set their master page in the code. In such case you can also set any theme or skin to your page, in PreInit we can also set the properties of the server controls of Master page, like the code below:

protected void Page_PreInit(object sender, EventArgs e)
{
if (textBox1 == null)
       {
          Response.Write("Pre Init, server control Not available");
       }
       else
       {
          string TextinInit = textBox1.Text;
          Response.Write("Pre Init, Server Control enabled");
       }

Page.MasterPageFile = "~/TestInitMaster.master";

       TextBox _mstTextBox = (TextBox)Page.Master.FindControl("txtMessage");
       Label _mstLabel = (Label)Page.Master.FindControl("lblMessage");

       _mstLabel.Text = "Setted in default page at time : " +ateTime.Now.ToString();
       _mstTextBox.Text = "Textbox set in default page";
  }

In above you can see I’ve used a master page dynamically and set a label and TextBox’s Text property of that master page in runtime that means we can set the master page dynamically and associate the values in their controls if any. If you try to set the masterpage in any other event after Page_PreInit event, you will get an error message that will tell you that the master page only can be set on or before Page_PreInit event. In Page_PreInit event you can also see at the top level I’m checking a TextBox1 value whether it’s null or not. It is a server control (TextBox), but in PreInit the value will always be null of this text box or any other server control. So if I want to conclude the thing, in Page_PreInit controls are not fully initialized. So use this event for setting MasterPage file in your code. Each control Unique ID’s are also available at this event.

Init  
Init is called when you can initialize your page controls, this is the place that comes into picture after each Control initialization, till this event they get their Unique Id, master page etc. In Init you cannot access any controls properties after the last viewstate, I mean suppose you enter some text in a textbox control and click on a button control that makes a postback, now you want to view the value latest entered. In such case you will be able to see the textbox value which you’ve entered after the round trip happens, this is because of ViewState property of controls. That means they preserved your last saved value, but you see this value after Init phase because, usually we don’t use these events in our code and use just Page_Load event where the Viewstate value already got loaded. But as in Init phase, we cannot access our latest entered values in textbox, so in Init you won’t be able to get the latest changes. So I can say in Init we won’t be able to get the postback value.

InitComplete
In this event, Viewstate functionality is turned on for server control. Viewstate of controls allows preserving their values across postback.

PreLoad
This is the first event where viewstate functionality starts retrieving their values. PreLoad executes after InitComplete method. In this method, page has loaded values from viewstate. So for example in a button click event if you create a viewstate like below than what will going to be happen:

protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ViewState["myData"] = "just a text string";
        }

After button click, postback will happen at it will start calling page events like PreInit, Init, Initcomplete. Till these three events you will not be able to get the value of Viewstate “myData”. Even when the event fires PreLoad event of page, at this time you cannot access the ViewState, this is because ViewState will set the value when asp.net reaches the ButtonClick event, and this will happen after Load event, so one more time we will click on our submit button, and because now the ViewState[“myData”] resides into my page, I can access it on my PreLoad event. For better understanding please see the screen shot below:
ASP .Net page life cycle

Load
Most of the developers are familiar with the page load, as this is the only event that comes by default in aspx.cs page when you start doing anything with your code behind. The page Load events executes after the Page_PreLoad event. If you have created your own Load method in constructor of your code behing, then this will be the method that will execute before the Page_Load event and after Page_PreLoad event, for better understanding refer to the image below:
Init event in Page Life Cycle


As you are seeing in above code, I’ve created my own Page_Load event in my code behind as well as the default Load event, I didn’t mention Page_PreLoad event here, but it will execute after Page_InitComplete event. So back to the image, the _Default_Load will execute first before the Page_Load event. If you have any master page in your page, then the Load event of your master page will run followed by the user control Load event if they exist in your file.

Events
After the Page_load the next event is Page Control’s event. For example, if you have a control that raises postback just like button, and you clicked on the Button, so after Page_Load your Button_Click event will fire, and do the rest of the thing you’ve mentioned in your page. for better understanding please refer to the image below, event execution will be happen in that sequence how image is showing, in event portion whatever you will do that will go ahead and will do the things you’ve mentioned in you page. just like below, I said to create a ViewState[“myData”] and put some string inside that viewstate. So now the viewstate is ready to preserve ahead in my code. 

In Events you can also check the Page.IsValid property if you’ve used any validator controls in your page like regularexpressionValidator, requiredFieldValidator, Range etc. To check this property refer to the image below.
Load complete event of Page Life Cycle


LoadComplete
This event can be used when all the event processing has been done in the page.

PreRender/PreRenderComplete 

PreRender event gets called when page has created all the controls that user will see in his browser. PreRenderComplete is the last place to change anything in the page. After this event any changes will not get preserved in page cycle. 

SaveStateComplete
event gets fired immediately after the PreRenderComplete event, in this event the viewstate functionality and control state get saved, as I said in PreRenderComplete changes can be done that will affect the next postback. In SaveStateComplete you can do the changes in your server control, but the state won’t be available in next postbacks. 

Render 
Render is not an event but this is the phase where the HTML of your page will get rendered to the output stream with the help of HTMLTextWriter. You can override the Render method of page if you want to write your own code rather than the actual HTML text. As like below:

Render event of Page Life Cycle

As you can see in the code above, I’ve override the Render method in my code and write something with Heading 1 tag and later on called the base.render method. In current scenario the thing will happen is: apart my server controls code in my browser I’ll be able to see my Hello world text also. If I remove the base.render method calls, than I won’t be able to view my any control if I’ve created in page.


Unload 
This is the last event that gets fired. This is the page cleaning process like closing the open file connections etc, so in this process you cannot do any kind of manipulation with data that affect the rendering, you are restricted to use Response property also, and doing such you will get an exception message.

There might be some mistakes with this article but I tried my best to share with you, So if you have some queries OR suggestions please feel free and share the by comment. Thank you for reading this post..



Page_PreInit

Page_Init

Page_InitComplete

Page_PreLoad

Page_Load

Page_LoadComplete

Page_Prerender

Page_PrerenderComplete

Page_SavestateComplete

Page_Unload








--------------------


That's why I was pretty amused the other day when I happened to run across SILVER-U, which is a mnemonic device for remembering the ASP.NET page lifecycle. Here are the steps, along with the methods you'd most commonly want to handle or override at each step:
  • S - Start. (OnPreInit)
  • I - Initialize. (OnInit, InitComplete, OnPreLoad)
  • L - Load. (OnLoad)
  • V - Validation. (Validate)
  • E - Event Handling. (OnLoadComplete, OnPreRender, OnSaveStateComplete)
  • R - Render. (Render)
  • U - Unload. (OnUnload)
I thought this was kinda cool, so I'm passing it on.
Of course, this won't be replacing my all-time favorite, which applies equally well to ASP.NET as it does to life: PPPPPPP.


It can be difficult to remember exactly what happens and when during the ASP.NET page lifecycle. That in mind, often the easiest way to make sense out of a series of steps is to create an acronym. Microsoft shows us the basic steps of the ASP.NET page lifecycle below.
  1. Page Request
  2. Start
  3. Page Initialization
  4. Load
  5. Validation
  6. Postback event handling
  7. Rendering
  8. Unload
Putting together an acronym for these is easy enough. Since the Page Request technically isn't a part of the life cycle (it only indicates whether we actually will start the cycle or load a cached page) we won't include it in the acronym.
  • S – Start
  • I – Initialize
  • L – Load
  • V – Validate
  • E – Event Handling
  • R – Render
That gives us "SILVER", which is very easy to remember. However, it is important remember that the last part of the cycle is unload. You can remember it as "SILVER-U" or "SILVER-YOU" if that helps (but it just didn't quite fit into our acronym!). Now that it's easy to remember the order of steps for the page lifecycle, we'll summarize exactly what happens and what events are pertinent to each stage.

codeproject 
UsualDosage
Web Developer

First, you need to understand what is the Life Cycle of an ASP.NET page?
When you open a web page in the browser, it sends a request to the server and server processes this request and returns a page to the browser. This complete process is known as Life cycle of a page.
How it starts: The life of an ASP.NET page starts when the page is first requested by the user.
How it ends: It ends when the page is rendered completely to the browser.
Until now, it's simple. On the server side, the processing of an ASP.NET page is done in stages. At each stage, some events are fired. With these events, you can write your own code to handle any processing logic in ASP.NET page.
Now I will explain the different stages of ASP.NET page life cycle. I have seen many explanations of the Page Life cycle and none of them could make it into my favorite list. All the articles were very lengthy and complex. I will try to explain it in the simplest language with a clarity of thought.
Here are the list of stages:
I am writing this tip to explain the life cycle of the page. So I try to simulate and experience the complete life cycle of an ASP.NET page on my laptop. What I will do? I will start my browser and open an ASP.NET page. Then will tell you the complete story of the ASP.NET page life cycle right from when I start typing the page URL in the browser to final rendering of the page in my browser.
Let's start!
  1. Browser makes a request:I open my browser Mozilla and type the URL of an ASP.NET website. Let's say I typed http://woodland.com/. What does it means? This means that I made a request to the browser to open this page for me. Browser will send my request to the server on which this page is hosted.
  2. Page framework initialization: Page.Init event firesASP.NET checks whether the request is a new one or an old one. If the request is a new one, then ASP.NET creates the page. It generates the page with all the controls defined in the .aspx page.
    If the page request is an old one, then ASP.NET gets the data from View state and sets all the controls status View State information and page is returned to the browser.
  3. User Code Initialization: Page.Load event fires.In this event, initialization is done. Populating the dynamic controls or dropdown list is done in this event. This event always fires whether the page requested for the first time or page is requested as part of a postback. Initialization is to be done only on the first request. On a postback, you have to do nothing, ASP.NET restores the control properties automatically from View State information.
  4. Validation: After the page is loaded, validation controls gets fired and displays error messages. You just have to check whether the Page.IsValid is true or false.
  5. Event handling: Now the page is fully loaded and validated. This stage includes any events that fired after the last postback. There are 2 types of events in an ASP.NET page life cycle:

    1. Immediate Response events: For eg. Button click, link click, etc. These events trigger a postback immediately.
    2. Change Events: For example: Changing the selection in a dropdown list or in a Textbox. These events fire when the page is posted back next time.
  6. Browser receives response: Response and request properties of the page are unloaded and any cleanup operation if required is performed.Example: I believe that there is nothing better than an example to explain things. So I am providing you a page with a sample scenario.
I have created a page with a Textbox and a submit button. I have written some text in Textbox and click submit button triggering a Postback. Here is the list of events that fires in this example:

  1. Page.Init
  2. Page.Load
  3. Textbox.TextChanged
  4. Button.Click
  5. Page.PreRender
  6. Page.Unload
I hope the above explanation has given you a clear idea of how ASP.NET page executes and runs. You can use these events to write optimal and perfect code for your projects.




Recent Articles


















No comments:

Post a Comment