Tuesday, September 4, 2007

ASP.NET Page Templates - Using Inheritance

Introduction

Anyone who has developed commercial websites has run into the problem of creating a template for the site. For most sites a large percentage of the HTML is the same or similar for all pages. The header, navigation, and footer elements of a typical site layout appear on almost every page.

Some developers will put that markup in every page's source file. Anyone who's had to maintain a site put together this way knows how difficult it is to make site-wide changes. You end up depending on massive search and replace operations, which can be difficult to do without creating markup errors that require hand-tuning to repair.

In traditional ASP programming, like many other server-based programming environments, this was typically solved using an include file. The page is divided into logical sections representing the header, left navigation, body, and footer elements. A separate include is created for each of the common elements and the body section is placed in the actual ASP page. The page then includes the appropriate files to build up the look and feel of the page. This is a significant improvement over the previous approach, but still creates a few maintenance problems.

First of all, the individual ASP files must contain the code necessary to include the correct support files. This makes each page's content strongly coupled to the site's template. It also means that when you add a new page to the site, you must remember to setup all the correct includes in the right order.

An additional problem happens when you decide to make a significant look-and-feel change to the site. If you're lucky, you may be able to make all of your changes in the include files. Most of the time, however, the tight coupling between the include files and the ASP pages means that you end up having to edit each and every ASP page as well.

With the introduction of ASP.NET, developers have been giving a powerful new set of tools to help resolve these problems. ASP.NET uses an object-oriented development paradigm. In practical terms this means that every page is a class that derives from System.Web.UI.Page. This class provides a number of services to the web developer including caching, rendering, response and request access, etc.

So the question is: How can we best take advantage of the object-oriented nature of ASP.NET when creating websites? Is there a better way to create templates than using include-files?

No comments: