Sub-Classing the Page Object


The Page class is the base class you will generally use directly in your Web Forms pages and ASP.NET Web applications. However, you can extend the standard Page class if you wishperhaps by adding new methods or just changing the default settings of some properties to better suit your own requirements.

For example, Listing 9.17 shows the declaration of a class named MyBasePage that inherits from the standard ASP.NET Page class. It sets the ErrorPage property to a specific value and adds a new custom read/write property named MyProperty to the class. It also handles the PreInit event and looks for a value in the current user's profile to see if a Theme was specified by the user. If so, it sets this theme on the page using the Page.Theme property. Notice that the code first calls the OnPreInit method of the base Page instance.

Listing 9.17. The Base Class for Pages, Based on the Existing Page Class

public class MyBasePage : System.Web.UI.Page {   // set an existing property for all pages   ErrorPage = "MyErrorPage.aspx"   // add new property to all pages   protected string _myProperty;   public string MyProperty   {     get { return _myProperty; }     set { _myProperty = value; }   }   // force all pages to use current theme   protected override void OnPreInit(EventArgs e)   {     base.OnPreInit(e);     if (HttpContext.Current.Profile.GetPropertyValue("Theme") != null)       Page.Theme = HttpContext.Current.Profile.GetPropertyValue(                                             "Theme").ToString();   } }

Now, other pages can inherit from this new base page. In the @Page directive, when using the code-behind model, the pages will specify a partial class file that implements the code for the page; for example, this declaration specifies a file named Default.aspx.cs that implements a partial class named _Default:

<%@ Page Language="C#" AutoEventWireup="true"          CodeFile="Default.aspx.cs" Inherits="_Default" %>


Listing 9.18 shows how the code in the file Default.aspx.cs can access the new custom property named MyProperty just as it would access any other property of the Page class.

Listing 9.18. Specifying the Base Class and Setting the Custom Property

public partial class _Default : MyBasePage {     protected void Page_Load(object sender, EventArgs e)     {         MyProperty = "Some new value";     } }



ASP. NET 2.0 Illustrated
ASP.NET 2.0 Illustrated
ISBN: 0321418344
EAN: 2147483647
Year: 2006
Pages: 147

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net