Eric Anastas Eric Anastas - 29 days ago 6
ASP.NET (C#) Question

Can two ASPX pages inherit the same code behind class?

I'm just starting out learning ASP.NET. From what I understand, ASP.NET differs from old school ASP in that the logic code for a page exists in as separate file rather then being embedded in the ASP page. So when a user requests a page like ShoppingCart.aspx the server reads the directive at the top ...

<%@ Page Title="" Language="C#" MasterPageFile="~/Styles/Site.Master" AutoEventWireup="true"
CodeBehind="MyShoppingCart.aspx.cs" Inherits="TailspinSpyWorks.MyShoppingCart" %>

This tells the server what file and what class in the file is associated with the page. The code behind class also has member variables that correspond to each control on the page, and provide a way for code in the code behind file to manipulate the controls.

First, do I understand this correctly?

Second, could a site be setup with two separate ASPX pages with identically named controls, which both had a directive pointing to the same file and class? Would you even want to do this? Both pages could have the same functionality but a different layout. I was thinking this could be a way to create separate "desktop" and "mobile" versions of a page with out duplicating content in the code behind files.

I guess ultimately what I'm wondering, is if there a way to define an abstract page? Say create an abstract page definition that says a page must have controls "cart_list", "total_lbl", but then be able to have multiple pages that inherit from this abstract page?


Yes, two pages can inherit from the same class. Like it can inherit from Page class directly and do not even have an associated .cs file (useful when you have a page which is not static, but which does not handle events or something which may require a code-behind class).

In practice, I think it's not a good idea to inherit several ASP.NET pages from the same class directly. This is not something common, so:

  • the code will be more difficult to understand and impossible to extend,
  • will be difficult to manage within Visual Studio, especially when it comes to events, controls, etc.
  • will cause much pain with existing/missing controls. See the detailed Guffa answer below.

If several pages of your website share the same logic,

  • make one class per page, and inherit those classes from a common parent class which will contain common methods and properties and which will inherit from Page class. You will obtain an extensive and easy-to-understand solution.
  • or create a masterpage if the case is a good candidate for a masterpage.