Sep 24 2007

BasePage and Page interaction in ASP.NET

Category: Design Patterns in ASP.NETBil@l @ 18:54

I am focusing these days on covering the different design patterns available for developing Web Applications. A very nice technique I have learned.

Suppose you have several pages in a Web application, as you know we have several events that fire during the page-life cycle. What if you want to have some common code in any event fired during the page life cycle, for this example suppose it is Page_Load. At the same time, you need every page in the Web application also to add some code processing into the page_load event. How will you solve it?

A very nice technique that I personally like explained below:

Create the BasePage.cs as follows:

public class BasePage : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Hello World From BasePage <br/>");

        PageLoad(sender, e);
    }

    virtual protected void PageLoad(object sender, EventArgs e)
    {
    }
}

Notice the virtual method defined in the BasePage class above. The reason it is virtual is to give each page in the Web application inherirting from this BasePage the chance to add additional code to be executed inside the Page_Load. As you can see also, I am calling the PageLoad inside the Page_Load method.

A page in the Web application can be implemented as follows:

public partial class _Default : BasePage
{
    protected override void PageLoad(object sender, EventArgs e)
    {
        Response.Write("Hello World from Page");
    }
}

In an ASP.NET page, I simply inherit from the BasePage and then override the PageLoad method!!

This way, when the page is requested, the Page_Load inside the BasePage is executed first, and implicitly the PageLoad is executed if it is implemented by the child page.

Hope you like this technique!

Thanks

 

Tags:

Comments are closed