The ASP. NET page Life Cycle

Source: Internet
Author: User
URL: http://www.15seconds.com/issue/020102.htm

Introduction

When a page request is sent to the Web server, whether through a submission or location change, the page is run through a series of events during its creation and disposal. when we try to build ASP. net pages and this execution cycle is not taken into account, we can cause a lot of headaches for ourselves. however, when used and manipulated correctly, a page's execution cycle can be an effective tive and powerful tool. developers developers are realizing that understanding what happens and when it happens is crucial to define tively writing ASP. net pages or user controls. so let's examine in detail the ten events of an ASP. NET page, from creation to disposal. we will also see how to tap into these events to implant our own custom code.

I'll set the stage with a simple submission form written in ASP. net with C #. the page is loaded for the first time and has several server-side Web controls on it. when the Web server receives es a request for the page, it will process our Web controls and we will eventually get rendered HTML. the first step in processing our page is object initialization.

  • Download source code
  • View demo

1. object initialization

A page's controls (and the page itself) are first initialized in their raw form. by declaring your objects within the constructor of your C # code-behind file (see figure 1), the page knows what types of objects and how to create. once you have declared your objects within your constructor, you may then access them from any sub class, method, event, or property. however, if any of your objects are controls specified within your Aspx file, at this point the controls have no attributes or properties. it is dangerous to access them through code, as there is no guarantee of what order the control instances will be created (if they are created at all ). the initialization event can be overridden using the oninit method.


Figure 1-controls are initialized based on their declaration.

2. Load viewstate data

After the init event, controls can be referenced using their IDs only (No Dom is established yet for relative references ). at loadviewstate event, the initialized controls receive their first properties: viewstate information that was persisted back to the server on the last submission. the page viewstate is managed by ASP. net and is used to persist information over a page roundtrip to the server. viewstate information is saved as a string of name/value pairs and contains information such as control text or value. the viewstate is held in the value property of a hidden <input> control that is passed from page request to page request. as you can see, this is a giant leap forward from the old ASP 3.0 techniques of maintaining state. this event can be overridden using the loadviewstate method and is commonly used to customize the data stored ed by the control at the time it is populated. figure 2 shows an example of overriding and setting viewstate at the loadviewstate event.


Figure 2-When loadviewstate is fired, controls are populated with the appropriate viewstate data.

3. loadpostdata processes PostBack data

During this phase of the page creation, form data that was posted to the server (termed PostBack data in ASP. net) is processed against each control that requires it. when a page submits a form, the framework will implement the ipostbackdatahandler interface on each control that submitted data. the page then fires the loadpostdata event and parses through the page to find each control that implements this interface and updates the control state with the correct PostBack data. ASP. net updates the correct control by matching the control's unique ID with the name/value pair in the namevaluecollection. this is one reason that ASP. net requires unique IDs for each control on any given page. extra steps are taken by the framework to ensure each ID is unique in situations, such as several Custom User Controls existing on a single page. after the loadpostdata event triggers, The raisepostdatachanged event is free to execute (see below ).

4. Object Load

Objects take true form during the load event. all object are first arranged in the page dom (called the control tree in ASP. net) and can be referenced easily through code or relative position (crawler the DOM ). objects are then free to retrieve the client-side properties set in the HTML, such as width, value, or visibility. during load, coded logic, such as arithmetic, setting control properties programmatically, and using the stringbuilder to assemble a string for output, is also executed. this stage is where the majority of work happens. the load event can be overridden by calling onload as shown in figure 3.


Figure 3-the onload event is an ideal location to place logic.

5. Raise PostBack change events

As stated earlier, this occurs after all controls that implement the ipostbackdatahandler interface have been updated with the correct PostBack data. during this operation, each control is flagged with a Boolean on whether its data was actually changed or remains the same since the previous submit. ASP. net then sweeps through the page looking for flags indicating that any object's data has been updated and fires raisepostdatachanged. the raisepostdatachanged event does not fire until all controls are updated and after the load event has occurred. this ensures data in another control is not manually altered during the raisepostdatachanged event before it is updated with PostBack data.

6. Process client-side PostBack event

After the server-side events fire on data that was changed due to PostBack updates, the object which caused the PostBack is handled at the raisepostbackevent event. the offending object is usually a control that posted the page back to the server due to a state change (with autopostback enabled) or a form submit button that was clicked. there is often code that will execute in this event, as this is an ideal location to handle event-driven logic. the raisepostbackevent event fires last in the series of PostBack events due to the accuracy of the data that is rendered to the browser.

Controls that are changed during PostBack shocould not be updated after the executing function is called due to the Consistency factor. that is, data that is changed by an anticipated event shoshould always be reflected in the resulting page. the raisepostbackevent can be trapped by catching raisepostbackevent, as in Figure 4.


Figure 4-The raisepostdatachanged and raisepostbackevent events are defined by the ipostbackdatahandler interface.

7. prerender the objects

The point at which the objects are prerendered is the last time changes to the objects can be saved or persisted to viewstate. this makes the prerender step a good place to make final modifications, such as changing properties of controls or changing Control tree structure, without having to worry about ASP. net making changes to objects based off of database CILS or viewstate updates. after the prerender phase those changes to objects are locked in and can no longer be saved to the page viewstate. the prerender step can be overridden using onprerender

8. viewstate saved

The viewstate is saved after all changes to the page objects have occurred. object State data is persisted in the hidden <input> object and this is also where object state data is prepared to be rendered to HTML. at the saveviewstate event, values can be saved to the viewstate object, but changes to page controls are not. you can override this step by using saveviewstate, as shown in Figure 5.


Figure 5-values are set for controls in onprerender. During the saveviewstate event, values are set for the viewstate object.

9. Render to HTML

The render event commences the building of the page by grouping the HTML for output to the browser. during the render event, the page callon the objects to render themselves into HTML. the page then collects the HTML for delivery. when the render event is overridden, the developer can write custom HTML to the browser that nullifies all the HTML the page has created thus far. the render method takes an htmltextwriter object as a parameter and uses that to output HTML to be streamed to the browser. changes can still be made at this point, but they are reflected to the client only. the render event can be overridden, as shown in Figure 6 (below ).

10. Disposal

After the page's HTML is rendered, the objects are disposed. during the dispose event, you shoshould destroy any objects or references you have created in building the page. at this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page Object. you can override dispose, as shown in figure 6.


Figure 6-The render event will output custom HTML to the browser through the htmltextwriter object.

Conclusion

Each time we request an ASP. NET page, we run through the same process from initialization to disposal. by understanding the inner workings of the ASP. NET page process, writing and debugging our code will be much easier and valid tive (not to mention less frustrating ).

Appreciation

I wowould like to thank my wife for her support through the years. I wowould also like to thank my colleagues, Dean Anderson, Joe slovinski, and Bill altvater, for their continued help.

About the author

Solomon Shaffer has been in the information technology industry for five years. while attending college in pittstmgh, Pennsylvania, he founded cynthetic, inc ., A software-development practice focused on Microsoft Internet technologies. solomon's areas of expertise include com development, ASP, SQL, and UI layout/design.

Solomon is currently working on building the next-generation Web applications using. NET platform in Nashville. at press time, he has over nine months of enterprise. NET development experience, developing enterprise applications with the platform since its beta 1 release.

Solomon and his wife reside in Atlanta. He can be reached at solomon.shaffer@cynthetic.com.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.