Effective interaction between user controls and parent container
In this article I'll cover topics related to the interaction between user controls and
parent container (parent page).
In the classic ASP, when we had similar layout elements for a set of pages,
we were forced to use dynamic includes. This is quite a good solution, because
it allows to get rid of repeating code, but, nevertheless, there are some flaws
in it. Just for example, there were many problems related to virtual paths in those
include files - one had to keep track of all such entries in the include files, because
it could cause problems after deploying to a web site with another configuration.
Moreover, when we speak about .NET world, we should keep in mind one of the key benefits of ASP.NET platform - code
separation from implementation layer. This means that if we want to keep purity of this concept,
we have to get rid of dynamic includes and replace them with a user controls.
So, how user control can interact with the parent page class which it declared in? Of course,
it can expose some properties, but this is what I call "static interaction" - you just can set or get
some of the user control's properties. More interesting thing is a "dynamic interaction", when
some of the user control events could be handled in parent page class. This is also called "event bubbling".
So here you can see short and simple example of it. User control contains
dropdown list and event handler for it. This event handled not only in the user control,
but in the page class as well.
Let's take a look on what's happening. When user changes selection of this dropdown list,
and makes new request therethrough, first of all Page_Load() method of parent page container is fired.
At this moment user control is loaded and then Page_Load() method of this control class is fired. Then control is
passed to the event handler in the user control, and, finally event is "bubbled" back to the parent
page class and special event handler for this event is fired there. So, that's the sequence of called methods.
This allows to execute some code in the parent page class after user control rendering, what is very useful option.
Here you can see user control code:
|
|