ASP.NET Web Page Code Model

A Web page is made up of the following two components:

    1. The Visual portion

    2. The programming logic

ASP.NET provides two models for managing the visual elements and code:

    1. Single-file page model

    2. Code-behind page model

The Single-file Page Model

In the single-file page model, HTML markup of the page and its programming code are in the same physical .aspx file.

The programming code is contained in a <script> block that specifies the attribute runat="server".

Te first line in the .aspx file contains the @Page directive. The @Page directive provides ASP.NET with the basic information about how to compile the Web page. It also indicated the language that will be used for coding and the way to connect the event handlers. The syntax of the page directive is:

<%@ Page Language="C#"%>

At run time, the compiler converts a single file page into a class that derives from the System.Web.UI.Page class.

The Code-Behind Page Model

In the code-behind model, HTML markup is kept in one file (with extension .aspx) and the programming code in another (with extension .cd or .vb). The code file contains a partial class, which indicates that the class contains only some of the total code that makes up the full class for the page. The partial class inherits from a base class (either System.Web.UI.PAge or a class derived from System.Web.UI.Page).

There are two differences in the .aspx page between the single-file and the code-behind models:

    • In the cod-behind model, there is no <script> block with the runat="server" attribute.

    • In the code-behind model, the @PAge directive contains attributes that refernce an external file and class, as shown in the following example:

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

In the preceding example, the CodeFile attribute specifies the cod-behind file with which the page is associated, and the Inherits attribute specifies a cod-behind class for the page to inherit. This class can be any class that is derived from the Page class. This attribute is used with the CodeFile attribute which contains the path to the source file for the cod-behind class.

When the page is compiled, ASP.NET creates a new partial class for the .aspx file. This class is a peer of the cod-behind partial class file and contains the declarations for the controls of the page. Finally, ASP.NET generates a class that inherits from the partial class created from the .aspx file and the code-behind partial class. The generated class is compiled into an assembly that runs in order to render output to the browser.