Base Page and User Control Classes
page 1 of 1
Published: 17 Oct 2003
Unedited - Community Contributed
Abstract
Create a custom base class for pages and user controls and gain flexibility for adding functionality to all pages and user controls on a site.
by Robert Boedigheimer
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 81511/ 103

Background

By default, new web forms (.aspx) that are added to an ASP.Net project derive from the class System.Web.UI.Page, and new user controls (.ascx) derive from System.Web.UI.UserControl. These classes both provide many useful properties, methods, and events that can be utilized in our own pages and user controls. A useful technique to employ for all ASP.Net web sites is to create a custom class for all pages and user controls for a web site. The idea is to create a class that derives from System.Web.UI.Page, and then to change all the pages on a web site to derive from this new class. This provides a single place where behavior can be altered for all pages on the web site. The concepts are identical for user controls, so this article will focus on the System.Web.UI.Page class, with the same technique applying to the System.Web.UI.UserControl class as well.

At first this seems like just another way to provide common code for a web site, such as just using another assembly or another class in the same project. The difference, however, is that funtionality can be added to the single base class, and it affects how all other pages on the site behave without any other changes required. One example where using this technique proved very useful was when we had some issues with the default client side viewstate and were able to convert to use server side viewstate by only making changes to the custom base page class rather than all the web pages (see Server Side Viewstate for details).

Implementation

First it is necessary to create the new custom base page class, just create a new class file and derive from System.Web.UI.Page (the other code here is for the sample described):
public class CustomBasePage : System.Web.UI.Page
{
  //Example variable that can be set for all pages to access
  private bool bPrintView = false;

  public bool PrintableView
  {
    get
    {
      return bPrintView;
    }
  }

  public CustomBasePage()
  {
  }

  override protected void OnInit(EventArgs e)
  {
    //Always call the base method when override
    // so what it originally did can still happen
    base.OnInit(e);

    //Example that just reads a querystring that
    // should be supported for all pages
    if (null != Request.QueryString["Print"])
    {
      //Use try/catch in case value is not a boolean
      try
      {
        bPrintView = Convert.ToBoolean(Request.QueryString["Print"]);
      }
      catch
      {
        //Do nothing, just leave as false
      }
    }
  }
}

The key for this is to add the : System.Web.UI.Page after the class name. This specifies that the newly created class will derive from the existing System.Web.UI.Page class, so that all of the existing properties, methods, and events will still be available to our pages. The example shows one potential use of the custom base class, where it overrides the OnInit() event to check for a query string parameter. It then sets a local variable and provides a property PrintableView that our pages can access to see what the querystring parameter held. This method provides a centralized place where the custom class can get the proper value (with try/catch for safety) and yet every page can access the property to get the value.

Originally all of the pages on the site derived from System.Web.UI.Page like this:
public class WebForm1 : System.Web.UI.Page

Now they need to be changed to derive from the custom class like this:
public class WebForm1 : CustomBasePage

Conclusion

There are many opportunities to leverage a custom base class for pages or user controls. Establishing the rule that this technique will be put in place for all ASP.Net sites provides great flexibility in the event that some functionality must be added to every page or user control.

Send comments or questions to robertb@aspalliance.com.


User Comments

Title: good info   
Name: swati
Date: 4/6/2010 6:13:47 AM
Comment:
I like the above article but unable to understand how to implement

well, gd & rt info (theoraically)
Title: Very Good   
Name: Predrag
Date: 9/25/2008 12:30:04 PM
Comment:
Very good artical
Title: Re: Jagar   
Name: Robert Boedigheimer
Date: 9/2/2008 7:40:29 AM
Comment:
Unfortunately, since .NET itself does not allow multiple inheritance and the page and user controls derive from different classes it is not possible to make a single class that derives from both.
Title: base class for pages and user control   
Name: Jagar
Date: 8/31/2008 7:38:04 PM
Comment:
Is there anyway to make a base class for asp.net pages and user control, so that both the user controls and pages can inherit from the custom made class?
Title: Re: Kodster   
Name: Robert Boedigheimer
Date: 12/20/2007 7:49:25 AM
Comment:
I think what you are trying to accomplish is exactly why ASP.NET 2.0 created master pages. Master pages provide the ability to create a single standard layout to share across a series of content pages. I have seen people stretch the base page concept in ASP.NET 1.x to achieve similar purposes but don't personally recommend that approach if you can use master pages.
Title: How to update controls   
Name: Kodster
Date: 12/16/2007 8:50:04 PM
Comment:
Hi, I am using the same concept, but I have some controls in the derived class that has common functionality and wondered how I can make this work from a common base class. How can we declare the controls in a base class when it does not have an aspx file. Even if we do declare, we still need to have a layout for the controls in a page. Cannot do that without an aspx and the base class in concept is not designed to have a aspx. Any thoughts?
Title: Session   
Name: Zain
Date: 8/31/2007 8:30:23 AM
Comment:
Please help me for the sessionID, SessionExpired,
Title: Re: Ramu   
Name: Robert Boedigheimer
Date: 5/11/2007 10:02:15 AM
Comment:
I am not sure exactly what you looking for, the normal base class for code ASP.NET web pages is System.Web.UI.Page. Please email me at robertb@aspalliance.com if that is not what you were looking for.
Title: asp.net   
Name: ramu
Date: 5/9/2007 2:12:23 PM
Comment:
What is base class of ASP.NET
Title: Sr. Solution Developer   
Name: Moustafa Arafa
Date: 5/29/2006 3:09:50 AM
Comment:
Excellent article.
Title: Re: dharmendra   
Name: Robert Boedigheimer
Date: 4/4/2006 3:48:42 PM
Comment:
I am not sure I understand your question... If you want to know how to get rid of an active sesion for a user you can use Session.Abandon( ). If that is not what you need, please email me at robertb@aspalliance.com so we can discuss in more detail.
Title: Er   
Name: dharmendra
Date: 4/4/2006 1:56:31 AM
Comment:
hello i am dharmendra from nepal i have one problems pls tell me details about it. i want to close starting session when i am go to next page so pls tell me in details ok bye
Title: sounds great   
Name: Bhavesh
Date: 3/4/2006 2:55:02 AM
Comment:
I don't know much about asp .net, but this whole idea of central system ( making all work in a same way from one place ) sounds pretty good.
Title: it didnt work for me   
Name: Moazzam Ahmed
Date: 10/28/2005 4:07:17 AM
Comment:
hi

I followed your example, created a base web form called index.aspx, then created a second web form inherited from index. when I run it, it shows blank, no errors.

what am I doing worng?

Moazzam
Title: Re: Gary Woodfine   
Name: Robert Boedigheimer
Date: 8/12/2005 7:47:51 AM
Comment:
I setup a basic base page with an OnInit() and OnLoad() and a page that derives from it that includes an OnInit() and OnLoad() in C#. I ran a debug and watched and it only entered these events once for each (each of the four were executed once for the request as expected). You can email me at robertb@aspalliance.com if you want the sample or want to discuss more.
Title: Excellent   
Name: Gary Woodfine
Date: 8/9/2005 6:25:20 AM
Comment:
Great Work, I have used this concept a few times , but I must say this article has helped to clear up some thoughts I hav ehad to this problem.
However I have noticed in a recent implementation of this concept in VB.net , that may Page Init and Page load seem to fire twice on every request? is this normal?
Title: Re: Jim Heaton   
Name: Robert Boedigheimer
Date: 7/8/2005 8:41:22 AM
Comment:
I have seen problems with the IDE not opening properly with pages that have a base class, I have not seen it personally with the base user controls. I would start with an empty one and see if it works, then slowly add your other code until you discover which part is causing the issue. You can send to me directly at robertb@aspalliance.com to discuss...
Title: Good Article   
Name: Jim Heaton
Date: 6/30/2005 6:09:24 AM
Comment:
Excellent article - I was trying to implement a solution involving a base web user control with other web user controls derived from this but was having a problem because I was making the base user control as a .ascx file in its own right! Have implemented as described in your page example but have problems opening my derived controls designer with the VS IDE. It is coming up with a Type Abstract error. Do you know what Im doing wrong or is this just an IDE problem I have to live with? Note: can work around by designing with derived control inheriting usercontrol and then switching to base class but was just wondering if there was a more eloquent solution. Cheers, Jim.
Title: Re: Chaos   
Name: Robert Boedigheimer
Date: 5/9/2005 8:02:14 AM
Comment:
I just created an "empty" base page and derived from it and was still able to open the design view. Try that and then slowly add things from your base page until you can see what is causing it because it does not seem to be solely from the fact that it doesn't derive from System.Web.UI.Page. Send me an email to discuss further if desired.
Title: Visual Stuidio   
Name: Chaos
Date: 4/29/2005 4:29:16 PM
Comment:
When you inherit from a class that is not Page, you cannot open it with visual studio in design mode. Is there a way around this?
Title: Inheritance in asp, brilliant!   
Name: Andrew Silver
Date: 3/5/2005 6:38:27 AM
Comment:
This is great stuff. Certainly opens up a new level of web coding to me.
Title: Good work!   
Name: Chuck
Date: 8/26/2004 1:21:44 PM
Comment:
Excellent article and a real find, I will definetily be using this on my upcomming site redesign. Your other articles are also helpful and very easy to understand. Below is a close VB version of your snippet. Good work!

'Public Class CustomBasePage
' Inherits System.Web.UI.Page
'
' Private print As Boolean = False
'
' Protected Function isPrint() As Boolean
' Return print
' End Function
'
'
' Protected Sub Page_Init(ByVal sender As System.Object, 'ByVal e As System.EventArgs) Handles MyBase.Init
' If Request.QueryString("media") = "print" Then
' print = True
' Else
' print = False
' End If
' End Sub
'End Class
Title: good, simple explanation   
Name: stephen rylander
Date: 8/10/2004 9:09:42 AM
Comment:
This made sense and was easy to follow and use.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 10/31/2014 11:36:36 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search