The ASP.NET Page Cycle

Being a consultant, I have worked with a lot of other consultants - professionals within their domain. It has struck me how few of the ASP.NET developers have a clear understanding of the ASP.NET page cycle, something I think is crucial to be able to write effective code. Given this experience, I have compiled a quick cheat-sheet that illustrates some basic, important, points. Please note, however, that what you find below is a non-exhaustive, simplified, list.

The below page sequence is valid for instances of Control (Page inherits from Control):

  • Page_PreInit
  • Page_Init
  • Page_PreLoad
  • Page_Load
  • EVENT HANDLERS, eg. Button1_Click
  • If Page.Visible Then Page_PreRender

This means, that Page_Load always runs. If you have code that decides whether or not a page/part of a page/control is shown that is dependant on another control, put that code into Page_PreRender.

Example:

Public Sub Page_Load( ... )
  If Not IsPostBack Then
    LoadRegionalData()
  End If
End Sub

Public Sub Button1_Click( ... )
  _blnLoadHugeProductList = False
End Sub

Public Sub Page_PreRender( ... )
  If _blnLoadHugeProductList Then
    gvwProductList.DataSource = GetHugeProductList()
  End If
End Sub

Tip: If you have a bunch of user controls on a page, they will all load EACH TIME the page is loaded, even if they are hidden. To prevent this, remove them from the control collection in Page_Load of the owning page.

Comments

Popular posts from this blog

Auto Mapper and Record Types - will they blend?

Unit testing your Azure functions - part 2: Queues and Blobs

Testing WCF services with user credentials and binary endpoints