This blog has moved, permanently, to

Friday, June 19, 2009

The ASP.NET Page Life Cycle

The ASP.NET life cycle is as much a fantastic model for web developers as it is a pain the butt. Whenever I change jobs, I encounter different approaches to implementation of pages and controls, rarely with any regard to the correct order of doing things and usually with code that is very difficult to maintain as a result. If you can't rely on your controls to obey the page life cycle in terms of rendering, you've got a problem. For example, setting presentation properties during page load may cause trouble if developers set that property on events firing or during PreRender.

So, when should you do things? As a rule of thumb, I try to do data binding early (OnInit) and presentation setting late (OnPreRender, or in controls that output custom markup in the Render override). It's a tricky topic and something that seems to catch most developers - the concept of top-down development with classic ASP and PHP just doesn't apply.

There's an excellent article on MSDN about the order of events here:

For my future reference, some items to consider:
  • Init and Load need to be handled carefully: the Init event for controls fires BEFORE the Init event for the Page; the Load event for controls fires AFTER the Load event for the Page.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.