Developer

Common ASP.NET page functionality with inheritance

Here is how to create base pages that you may use to create other pages throughout the site.

ASP.NET 2.0's template page feature allows you to create base pages that you may use to create other pages throughout the site. This provides you with the ability to provide a consistent look and feel without the effort that the current ASP.NET release requires.

While this is a desirable feature, you may use inheritance with the current version of ASP.NET to provide a common backend structure for ASP.NET pages. Let's take a closer look at how you might apply this functionality with inheritance.

ASP.NET pages are based upon the Page Class, which is within the System.Web.UI namespace. Visual Studio .NET automatically uses it to create Web Forms pages. The Page Class is associated with files that have an .aspx extension. These files are compiled at run time as Page objects and cached in server memory. It provides numerous properties and methods. Here is a sampling of its properties:

  • Application gets the Application object for the current Web request.
  • Cache gets the Cache object associated with the application in which the page resides.
  • IsPostBack gets a value indicating whether the page loads in response to a client postback, or if it's loaded and accessed for the first time.
  • Request gets the HttpRequest object for the requested page.
  • Response gets the HttpResponse object associated with the Page. This object allows you to send HTTP response data to a client and contains information about that response.
  • User gets information about the user making the page request.

In addition, there are various methods/events triggered at various points in the object's lifecycle. Here are several of those events:

  • Error occurs when an unhandled exception is thrown.
  • Init occurs when the server control is initialized, which is the first step in its lifecycle.
  • Load occurs when the server control is loaded into the Page object.
  • Unload occurs when the server control is unloaded from memory.

All of the methods and properties are available in the Page Class as well as classes that extend it. Here is the C# code (code-behind file) for a basic ASP.NET page created with Visual Studio .NET:

namespace BuilderSamples {
public class SampleWebForm : System.Web.UI.Page    {
private void Page_Load(object sender, System.EventArgs e) {
// Put user code to initialize the page here
} } }

Here's an example page utilizing VB.NET:

Public Class SampleWebForm
Inherits System.Web.UI.Page
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
 System.EventArgs)
Handles MyBase.Load
'Put user code to initialize the page here
End Sub
End Class

Both code listings utilize the Page Class as their base, but you may easily replace this with a custom class.

Extending the Page Class

While extending the Page Class doesn't allow you to control a page's layout, it does allow you to include or execute backend code for every page using it as its base. For example, you may need to populate session variables, instantiate an object, set cache options, or possibly add JavaScript to the page.

The following code creates a base page class and performs the following tasks:

  • The class extends the System.Web.UI.Page class.
  • Caching is disabled.
  • A hidden field called statusFlag is created with a value of zero.
  • A JavaScript function is added to the head portion of the page.
  • JavaScript code is executed upon page startup/load.

The JavaScript code in the example is basic (alert statements), but they do show how you may use it. Also, the Visual Studio .NET's region (Web Form Designer generated code) is included.

using System;
using System.Web;
using System.Web.UI;
namespace BuilderExtendPageClassCSharp {
public class BaseClass : Page    {
public BaseClass() { }
private void Page_Load(object sender, System.EventArgs e) {
Response.Cache.SetCacheability(HttpCacheability.NoCache);
this.RegisterHiddenField("statusFlag","0");
this.RegisterClientScriptBlock("ExampleScript", @"
<script language=""JavaScript"" type=""text/javascript"">
<!—
function displayWindow() {
alert(""Sample JavaScript"");
}
//—>
</script>
");
this.RegisterStartupScript("startupScript",@"
<script language=""javascript"">alert('hello');</script>");
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e) {
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent() {
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
} }

Here's the VB.NET equivalent:

Imports System.Web
Imports System.Web.UI
Public Class BaseClass
Inherits System.Web.UI.Page
Public Sub BaseClass()
End Sub
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Handles MyBase.Load
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Me.RegisterHiddenField("statusFlag", "0")
Me.RegisterClientScriptBlock("ExampleScript", " " + _
"<script language=""JavaScript"" type=""text/javascript"">" + _
"<!—" + _
"function displayWindow() { " + _
"alert(""Sample JavaScript"");" + _
 "}" + _
"//—>" + _
"</script>")
Me.RegisterStartupScript("startupScript", "<script
language=""javascript"">alert('hello');</script>")
End Sub
#Region " Web Form Designer Generated Code "
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Private designerPlaceholderDeclaration As System.Object
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Handles MyBase.Init
InitializeComponent()
End Sub
#End Region
End Class

With the base class created, we can use this class in one or more application pages to provide the base functionality. In addition, it provides a central location to edit/maintain the code so it's easy to add more functionality to multiple pages from one point.

You could further extend this base class to add more functionality and to use it in multiple pages; that's one of the powerful aspects of object-oriented development.

The following page uses our sample C# base class to get its base functionality:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace BuilderSamples {
public class TestWebForm : BuilderSamples.BaseClass {
private void Page_Load(object sender, System.EventArgs e) {
if (!this.IsPostBack) {
Session["Test"] = "Test";
} }
#region Web Form Designer generated code
override protected void OnInit(EventArgs e) {
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent() {    
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
} }

The base class's load method is processed first, so the items added/processed in the base class are available to the child class. The VB.NET equivalent follows:

Public Class TestWebForm
Inherits BaseClass
#Region " Web Form Designer Generated Code "
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Private designerPlaceholderDeclaration As System.Object
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Handles MyBase.Init
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Handles MyBase.Load
If Not (Me.IsPostBack) Then
Session("Test") = "Test"
End If
End Sub
End Class

One of many options

Utilizing a class hierarchy is just one of the many options available within the .NET Framework. The creation of a base Page Class allows you to easily provide base functionality to a group of pages rather than adding it to each, thus easing the maintenance burden in the process. In addition, you may create Web controls to be included in one or more pages. The final choice is up to the developer, and ASP.NET 2.0 includes more options with template pages, making it a fan favorite.

TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically sign up today!

About Tony Patton

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

Editor's Picks