ASP.NET CodeFileBaseClass attribute versus inheritance with System.Web.UI.Page

I just created a base class for my pages, 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 are the pros and cons of any method? When will you use one over the other, or are they both the same? What happens if you use both at the same time?

+4
source share
1 answer

CodeFileBaseClass , CodeFile , Inherits work together with inheritance, and not instead of inheritance.

For example, if you specify CodeFile="page.aspx.cs" without page.aspx.cs existing, this will result in:

 Parser Error Message: The file '/page.aspx.cs' does not exist. 

Assuming page.aspx.cs exists, CodeFileBaseClass="PageBase.cs" without PageBase.cs existing will be:

 Parser Error Message: Could not load type 'PageBase.cs'. 

On the other hand, you can inherit from PageBase without by specifying the CodeFileBaseClass attribute. This can lead to unexpected behavior when linking to controls on a page from a base class.

To quote Microsoft @Page MSDN Documentation :

CodeFileBaseClass
Specifies the type name of the base class for the page and its associated code class. This attribute is optional, but when used, a CodeFile must also be present. Use this attribute if you want to implement a common scenario where you define common fields (and, optionally, related events) in the base class to reference the controls declared on the web page. Because of the ASP.NET code generation model, if you define fields in the base class without using this attribute, at compile time new member definitions will be generated for the controls declared on the web page (within a separate fragment of the partial class), and your The desired scenario will not work. But if you use the CodeFileBaseClass attribute to link the base class to 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), inherited from the base class, then the fields in the base class can refer to controls on the page after code generation.

+3
source

Source: https://habr.com/ru/post/1416486/


All Articles