The ASP.NET Page Life Cycle

By Solomon Shaffer

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 and powerful tool. Many developers are realizing that understanding what happens and when it happens is crucial to effectively 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 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.

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 many 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 received 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 (crawling 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 should not be updated after the executing function is called due to the consistency factor. That is, data that is changed by an anticipated event should 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 calls 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 assembling the HTML for output to the browser. During the Render event, the page calls on 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 of. During the Dispose event, you should 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 effective (not to mention less frustrating).

Appreciation

I would like to thank my wife for her support through the years. I would 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 Pittsburgh, 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 the .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.



Downloads

Comments

  • Breif and Informative

    Posted by Vincent on 06/12/2014 08:11am

    Thanks for the article. Suggestion for improvement: Note that figures 4, 5, and 6 are all the same image.

    Reply
  • http://linkssol.weebly.com/

    Posted by php on 04/09/2014 04:46am

    nice and informative post.thanks

    Reply
  • The ASP.NET Page Life Cycle

    Posted by Santosh Kumar Singh on 08/22/2013 10:12am

    THIS TOPIC IS VERY USEFUL FOR ME AND I GOT MORE INFORMATION FROM THIS SITE, THANKS............

    Reply
  • El simple, barato, mejor Peluquería Herramientas-ghd

    Posted by tqivpj649 on 07/17/2013 01:27pm

    pelo ghd es hermosa arma secreta peinado de una mujer. El famoso GHD es el encanto de la manera de conquistar a la mujer exigente y estilista? En primer lugar, entendemos el pelo ghd en los principales productos funktioner.GHD enderezador principales, técnica de calentamiento, principalmente de cerámica, el uso de la producción de calentador de cerámica y Corea del Sur, placa caliente, y se implanta la nanotecnología, la tecnología de infrarrojos y la tecnología de iones negativos, los productos , en su mayoría a cargo de luz de la superficie, elegante excelente calidad. Todos los productos son fabricados de acuerdo con la norma británica GS, seguro y confiable. rosa ghd sigue siendo el producto más vendido en 2011, esta GHD Qué encanto? [url=http://cheapghdoutlet.jimdo.com/]planchas ghd[/url] que esté limpio y seco. Para lograr un cabello hermoso saludable, tratar de calentar el champú protección y profunda condición de su aire limpio cabello. Use champú protección contra el calor en el proceso de consolidación para proteger su pelo y lo mantendrá tu cabello limpio y blød.dit cabello seco, toalla de microfibra, van a absorber una gran cantidad de agua, luego retire una toalla ordinaria, a continuación, aplicar dejar en el aire, lo que ayudará a mantener el cabello en el agua, para evitar extra seco y nervioso. Cepille su pelo, y luego secar al aire o secar el pelo. De cualquier manera, el cabello debe estar completamente seco antes de pelo ghd plancha ud.Når liso tu cabello es seco, ya está listo para usar su pelo liso, se debe aplicar para cada componente del derecho a postularse para el pelo liso ghd antes de usar un spray de protección contra el calor y el aerosol de suero brillo. Trate de evitar más de la misma sección de cabello nuevo. Cuanto más se puede causar más daño [url=http://comprar-ghd.manifo.com/]ghd baratas[/url] Hoy en dia, hay muchas herramientas para que podamos hacer nuestro cabello más style.men la plancha ghd es nuestra mejor opción, ya que puede tener el pelo más sano y fashion.I sugieren se lava el cabello y secarlo completamente antes de uso de alisadores. Si usted utiliza el pelo o cualquier otro planchas de pelo, causarán daños reparables para el cabello que está húmeda o no completamente tør.Vi ofrecen muchos tipos de Babyliss baratos GHD, marca de plancha de pelo ghd baratas, nueva llegada, descuento planchas ghd, etc nuevos estilos, buen precio, varios colores, entrega rápida, orden de la pequeña cantidad accepteret.Efter mi opinión, que vuelve a alegrar por la noticia de que ghd está preparado para you.All la ghd es muy chi y barato con una calidad superior. son absolutamente el mejor producto en el mercado.

    Reply
  • NdaLE OxI fIXw

    Posted by jZONeubQot on 06/22/2013 03:42pm

    http://mudchute.org/stats/vicodin/#81457 buy vicodin torn city - online doctors prescribe vicodin

    Reply
  • bilKul Bakwas.....................

    Posted by Akhtar on 06/07/2013 12:18am

    Non of the image is dispalying, so not understandable, please first correct you web site

    Reply
  • after i bought the clarisonic from david jones

    Posted by iouwanzi on 06/06/2013 07:51am

    [url=http://www.australiaclarisonic.com/clarisonic-classic]clarisonic classic[/url] modestes caractéristiques consistent non pas un mais deux défini guides mise en page talents Deco, simultanément disponible ce sont unique. Toute la galerie Scarlet comprend un sac soie cramoisi tolérant à chaleur merveilleuse lesoù aider à stocker le fer à lisser vos plaques ghd IV Styler cheveux pour s’assurer vous rose profond, par le biais de non pas un mais deux trucs cheveux sauvages dont une instance appropriée.Écrit à l’intérieur d’une boîte commune inflammed inanité habilitée par période de Style déco, tous le groupe écarlate fantaisie ghd styler intemporelle métal jaune comprend une alimentation réduite option rouge et en outre une mallette de rangement, un voyage fabuleux crinière sèche-cheveux ghd, couple de crinière de films et en outre un important carton satiné résistant à la chaleur. [url=http://www.miaclarisonicaustralia.org/]clarisonic mia online[/url] Cette approche ependant, juste pour un grand nombre de périodes à l’heure actuelle, toute l’entreprise collabore utilisant Jesse Lachapelle en raison des activités de publicité. (Queuwaaa ? Vous voulez ne sont pas au courant Jesse Lachapelle ? Petite et moyenne taille des classes de rattrapage pour tout le monde, par la suite. Fichier de l’ordinateur à ce moment, jeune padawan ! ) #) Afin d’améliorer la prochaine petite à moyenne taille relatives à la société photo, Document peut communiquer mon propre vraiment profiter de votre travail sur ce mec. Disputent au sérieux, à ce stade sa exploite ont tendance à être levé un grand métaphores ésotérique et un incroyablement puissant, particulièrement précis. Document adore ces sortes d’images, juste où chaque profondeur est importante à tout moment chaque parcelle est toujours à rencontrer ainsi que de lire. Interprétaton de l’individu la Pieta particulier revisité façon dont Courtney Love et Kurt Cobain (tristement prémonitoires…)#) me fascine particulièrement. Document inspirer un pour obtenir un déplacement sur différentes photos peuvent être trouvés avec son site Web. [url=http://www.australiaclarisonic.com/]clarisonic mia[/url] Et en outre s’il vous arrive d’entreprendre éventuellement pas le résultat dans n’importe quel élément spécifique excrètent partie sèche faire, Scarlett Discount Deluxe package en même temps se compose d’un sèche-cheveux et d’une journée itinérante corps temps, tous les trouvés dans une bonne suffisance vert magnifique.Document croire complètement heureux la saison yuletide aidera à faire.Atteignable cela viennent, individus sont faites de styler bijoux commun système vert, un étui propre fabuleux et même plusieurs clips et à vos cheveux, tout le de la couverture de tolérance incroyable chaleur de soie rose.

    Reply
  • Nous comprenons l'ouragan de sable a causé défis attainment beaucoup de nos clients

    Posted by cnbpitjay on 03/22/2013 10:19am

    Complexion attrayant, [url=http://www.hollistercoefrance.fr]hollister france[/url] des produits performants, legers, [url=http://www.abercrombiefrancevparis.fr]abercrombie[/url] pres du sol, respirant, confortable usure finest · · · · · · ces suffisent pas spew out decrire JORDAN 23, meme si c'est dans l'bourgeoning chaussure de signature, JORDAN 23 sont toujours lordly, aucune apparence matiere , de la viscosity of discernment et [url=http://www.airjordanfrpascherz.com]air jordan[/url] de la technologie, le concept est burden the drum fit aussi impressionnant. Christian Louboutin, un artist francais [url=http://www.abercrombieafranceusolde.fr]abercrombie[/url] de haut talons, est egalement bien connu a talons hauts chaussures de marque, chaussures a semelles rouges signature logo de Christian Louboutin. Dans le monde [url=http://www.hollisteruonlineshops.de]hollister online shop[/url] des talons hauts, Christian Louboutin est le Francais ne peut absolument pas etre ignoree. Il est le favori de l'actrice europeenne et americaine! Fait, d'ignorer aussi ne peut pas ignorer, [url=http://www.hollisterfranceamagesin.fr]hollister france[/url] cette marque de rouge a ne pas travailler, les femmes pieds des celebrites dans le cadre du rouge Nama retiendront votre attention. Il a rejoint le conseil de l'Université du Protection de Bonne-Espérance lors de sa création en 1873, même en tant que vice-chancelier à la fois. Il a fait un travail considérable en cette qualité peasant l'avancement des sciences naturelles [url=http://www.abercrombiexandfitchukes.co.uk]abercrombie uk[/url]. Il a également été membre du conseil du Collège diocésain, Pass Town.Smith était aussi très intéressé sedate la philosophie, et il a été impliqué dans la société sud-africaine philosophique depuis sa création en 1877. Il a également occupé le [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] poste de trésorier jusqu'en 1908, quand il est devenu Combined de la Baroness Fusing d'Afrique du Sud - nouvellement fusionnée pour l'Amalgamating d'Afrique du Sud. Il a re?u un doctorat honorifique en droit (LL.D.), en 1917.

    Reply
  • A launch vue, la Nike Dunk Sawn-off LR Thermo est une revealed and respected paire en daim et cuir noir et bien non Jordan

    Posted by Vetriatszy on 03/15/2013 01:24pm

    compare Abercrombie suits business and simply create improvement in how you look growing media with internet scientific knowledge contains shaped up the way of living. outfits blocks on dynamic. fashion accessory markets also has been raising, day-in-day. And vendors have at best resulted while using the promotion on television and web the computer industry. this advice replacements is continued and it'll keep on impacting on our life in a positive tactic accessorizing furthermore decorating has are more decided on. genders want show up completely different. They began to pay focus on every one item from the presents itself, be it about wearing or going to add accessories relating to unique situations. almost has been trends oriented. with a purpose to serve up the style ought of people young and old, hundreds and maybe thousands of designer holds and different labels will provide gadgets of varied benefits and fashoins. And this in retailing has been been modified. shopping on the web has be common. professionals wish to make an online purchase, for doing it has saved any morning. an increasing amount of brands hold his or genuine world wide web, and also this creates a chance for unquestionably the customers and prospects to shop online. Among all the websites, Abercrombie clothes business site is quite possibly the most visited ones. the clothes of your product have become well liked in which like better to shop by using this website. Now in an effort to there is an interconnection relating to the clients in addition Abercrombie fabric place. All those people, who definitely are careful, with regards to dress up, consumers love to go to our site always on sensible root, Just to be sure that they reach criminal on the compilation. web browsing this page can change your own self. You can physical appearance insanely favourable, just by searching by means information technology. You can keep on being the latest on newest compilation. in Abercrombie wardrobe web presence, you may get to see the garments of your liking. this website includes achieved substantive triumph, For you can use it certainly practical with kept up to date. it is extremely easy to access it. the collection, Which you view residence outlet stores having to do with Abercrombie and after that Fitch, equal attire are placed all over this site, so considering you are always bought most recent gathering in no way the existing one. the purpose at the staying the size of his web sensible and as well get the latest is to allow surfing effortless quick for you to the potential consumers. you will not have to issue regarding it site. Abercrombie clothings world-wide-web site is for your you in an entire course of action. you contact organization which enable you to find out as well as to solve a new inquires. from now on wonderful,it was a fun packed with expertise to shop for the clothes amongst Abercrombie or Fitch. customers and prospects feel really it happy and blessed they may have not end up being the devoted and also have forgot select the to items ture of every single company name. When you'll make purchases from this free movie blog, then you are without doubt,actually viewing often recommend friends to look by means of Abercrombie clothing rrnternet site. today retail therapy costumes is actually ask you to in your own time in your crowded practice life-style potentially go bad saturday your, except all you'll need to do is to grab a mug of coffees furthermore spend time looking at your laptop or computer. it's possible you'll do your own whole e-commerce shopping indoors matter of minutes and your products will range sign in doorstep few days. that which in addition click for more want to have

    Reply
  • What about dynamically created controls

    Posted by Markus Hanke on 11/20/2012 05:26am

    Hi, I am missing some words about dynamically created controls. Especially in an environment with several dynamically created controls, we figured there are phases in the lifecycle, where it is very unwise to depend on other controls (not being parents or children) as those might not be created already. Similaryl in the prerender phase, if several controls think, this is the last point where they are doing somehting, but communicating to other controls, destroying *their* assumption that PreRender has been the last point of action in the process. If you think it through, there remain only some phases/events where you can communicate freely with other controls, mainly RaisePostDataChanged and RaisePostBackEvent. What do you think about these lines of reasoning? Thanksful for any comment. -Markus Hanke

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • According to a recent Forrester total economic impact (TEI) study, enterprises can see a significant reduction in total cost of ownership by accessing Oracle Database in the cloud with a pay-as-you-go subscription model. This subscription service gives businesses the ability to scale up application environments for rapid prototyping, with far less time devoted to procuring licenses and deploying IT infrastructure. Read this study to learn how three different companies use Oracle Database in the cloud and the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds