Background
A popular technique for ASP.NET Web Forms developers for
years has been the use of a custom "base page" (http://aspalliance.com/63). The base page
class was a great place to put code that needed to be executed for each page on
the web site. This article discusses a new option to provide the same
functionality using the adapter framework.
Sample Project
Download the Visual Studio 2010 project that shows a
complete implementation of the techniques described [Download
Sample]
Implementation
Create a class that derives from
"System.Web.UI.Adapters.PageAdapter". Override page lifecycle events
that you want executed for every page request (like OnInit). Your code can
execute before or after the OnInit of each page depending on where you place
your code relative to the call to the original page event (referenced using
"base."). This example shows executing code before the OnInit of the
page fires. Don't forget to call the original event handler!
public class eventPageAdapter : System.Web.UI.Adapters.PageAdapter
{
protected override void OnInit(EventArgs e)
{
HttpContext.Current.Response.Write("Adapter OnInit<br>");
//Call this if want to have the corresponding page event fire
base.OnInit(e);
}
}
1.
Create a folder named "App_Browsers" in the root of the web
site
2.
Create a .browser file (such as "eventPageAdapter.browser")
and place it in the "App_Browsers" folder. The refID attribute
refers to which browsers you want to use the adapter for, in this case
"Default" means to use this for all browsers.
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.Page"
adapterType="eventPageAdapter" />
</controlAdapters>
</browser>
</browsers>
Benefits
There are several benefits of this approach compared to the
traditional "base page" implementation.
·
Don’t need to modify each code behind file to derive from the
custom base page class (it was not uncommon that developers would miss this
step and the base code would not be running)
·
Enable/disable without modifying other code in the site (you can
turn on/off the code by simply commenting out the controlAdapters element in
the .browser file)
Conclusion
This article explains the benefits of replacing the widely
deployed "base page" technique used in ASP.NET Web Forms with a page
adapter. The use of this new approach removes the need for developers to
remember to always derive from the custom base page each time they add a new
page to the web site.