Friday, August 14, 2009

Master Pages Events

Another master page twist that catches developers off guard is the order of the page lifecycle events. Let’s say we write the following code in our web form:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Write("Hello from Page_Load in default.aspx ")
End Sub


.. and the following code in our master page:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Write("Hello from Page_Load in Master1.master")
End Sub


Pop quiz: which Response.Write will appear in the output first?
Hint: most ASP.NET events are raised starting at the top of the control tree and working downward.
In this case, “Hello from Page_Load in default.aspx” will appear before “Hello from Page_Load in Master1.master”, because the content page’s Load event fires before the master page’s Load event.

Let’s set up another quiz using the following code in our content page.

Protected Sub Page_Init(ByVal sender As Object,ByVal e As System.EventArgs)
Response.Write("Hello from Page_Init in default.aspx")
End Sub


... and the following code in our master page.

Protected Sub Page_Init(ByVal sender As Object,ByVal e As System.EventArgs)
Response.Write("Hello from Page_Init in Master1.master")
End Sub


Pop quiz: which Init event will fire first?

Earlier we said most ASP.NET events work their way down the tree of controls. The truth is all lifecycle events (Load, PreRender, etc.) work in this fashion except the Init event. The initialization event works from the inside out. Since the master page is inside the content page, the master page’s Init event handler will fire before the content page’s Init event handler.

Obviously, problems will occur if the content page’s Load event handler depends on the master page's Load event to finish some work or initialize a reference. If you find yourself with this problem, or are worried about the order of events when a master page is involved, you might be too tightly coupled to the master page. Consider our earlier approach of using a custom event when when something interesting happens in the master page, and let the content page subscribe to the event and take action. This approach achieves greater flexibility.

No comments:

Post a Comment