I've just created a base class for my pages by inheriting from System.Web.UI.Page
:
public abstract class PageBase : System.Web.UI.Page
{
...
}
When I noticed that you can also declare a base page in an ASP.NET view:
<%@ Page Language="C#" CodeFileBaseClass="PageBase.cs" CodeFile="page.aspx.cs"
Inherits="page" %>
Can someone explain what the pros and cons of either method are? When would you use one over the other, or are they both the same? What happens if you used both at the same time?
CodeFileBaseClass
, CodeFile
, Inherits
work together with inheritance, not in place of inheritance.
For example, specifying CodeFile="page.aspx.cs"
without page.aspx.cs
existing will result in:
Parser Error Message: The file '/page.aspx.cs' does not exist.
Assuming page.aspx.cs
exists, specifying CodeFileBaseClass="PageBase.cs"
without PageBase.cs
existing will result in:
Parser Error Message: Could not load type 'PageBase.cs'.
On the other hand you may inherit from PageBase
without specifying the CodeFileBaseClass
attribute. This however could result in possible unexpected behaviour when referencing controls on the page from the base class.
To quote from Microsoft's @Page MSDN Documentation:
CodeFileBaseClass
Specifies the type name of a base class for a page and its associated code-behind class. This attribute is optional, but when it is used the
CodeFile attribute must also be present. Use this attribute when you want to implement a shared scenario, where you define common
fields (and optionally, associated events) in a base class to
reference the controls declared in a Web page. Because of the ASP.NET
code generation model, if you defined the fields in a base class
without using this attribute, at compile time new member definitions
would be generated for the controls declared in the Web page (within a
separate partial class stub), and your desired scenario would not
work. But if you use the CodeFileBaseClass attribute to associate
the base class with the page, and you make your partial class (its
name is assigned to the Inherits attribute and its source file is
referenced by the CodeFile attribute) inherit from the base class,
then the fields in the base class will be able to reference the
controls on the page after code generation.