The Code-Behind Approach

The Code-Behind Approach

The primary goal of the code-behind file is to enable you to write more modular code so that you can keep the code and layout physically separate. By keeping the code and layout separate, you can exploit the native object orientation of the .NET Framework to build a hierarchy of page classes that provide more and more specialized functions. As a result, you also have a little bit of page-level reusability, although you can’t reuse any elements of the layout.

With code-behind, you store directives and the page layout in one .ASPX file, and the code for them in a separate file written in Microsoft Visual Basic or Visual C#. The link to the code-behind file is defined by using an attribute of the @ Page directive.

<%@ Page Language="C#" Inherits="MyBasePageClass" Src="MyBasePage.cs" %>

When users point their browsers to the .ASPX page, the code-behind class file runs and dynamically produces the output for the page. When the page is requested, the code-behind file is loaded and treated as an integral part of the page.

A practical advantage of this approach is that it allows two programmers or programming teams to work on the development of a Web Forms page simultaneously. After the structure of a page is defined in terms of the number, names, and types of the constituent server controls, HTML designers can work on the appearance of the .ASPX file, determining the position of the controls, their colors and fonts, and even the client-side scripting. At the same time, Visual Basic and C# programmers can develop the code and the event handlers required for the page to work properly and fulfill user’s expectations.

Enabling Code-Behind

You enable the ASP.NET code-behind feature by adding a couple of attributes, namely Inherits and Src, to the @ Page directive.

<%@ Page Language="C#" Inherits="MyBasePageClass" Src="MyBasePage.cs" %>

The Inherits attribute contains the name of the code-behind class from which the current page inherits. The code-behind class can be any class derived from the Page class. The Src attribute represents the URL of the source file defining the class. When the ASP.NET HTTP run time processes a page, it first analyzes the @ Page directive. If Src is present, the code-behind file is loaded and compiled. Then the run time uses the contents of Inherits to get the name of the class to instantiate so that it can serve the ongoing page request.

Writing Code-Behind Pages

Any existing ASP.NET page can migrate to code-behind with very few changes. First you must write a class that inherits from Page. Next you add to the class, as a protected or public member, any control declared in the page layout that has the runat attribute set to server. Also, convert any global variable or procedure in the code section of the original ASP.NET page into a new member of the class with the scope and visibility you desire.


In the layout of an ASP.NET page, you declare controls using tag names. For those controls that you want to manipulate programmatically, when you switch to code-behind, you have to choose the control type and they must be non-private members of the class. You have to use the correct control class behind a given tag, for example, HtmlImage for <img>.

The following ASP.NET page has no <script> tag, yet it works. Figure 5-1 shows the page.

<%@ Page Inherits="BWSLib.CodeBehindPage" Src="CodeBehindPage.cs" %>
<html><title>Code-behind Page</title>
<body bgcolor="ivory" style="font-family:arial;font-size:small">
<form runat="server">
    <b><asp:label runat="server" Text="First Name"/></b>
    <asp:textbox runat="server" id="fname" />
    <b><asp:label runat="server" Text="Last Name"/></b>
    <asp:textbox runat="server" id="lname" />
Figure 5-1
A simple code-behind page.

The behavior of the page is determined by the code-behind file. The following code shows the code-behind file for Figure 5-1:

namespace BWSLib 
    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public class CodeBehindPage : Page 
        protected TextBox fname, lname;
        protected override void OnLoad(EventArgs e) 
            if (!IsPostBack)   
                // Set the style for the text boxes
                fname.Style["font-family"] = "verdana"; 
                fname.Style["border"] = "solid 1px black";
                fname.Style["background-color"] = "beige";
                lname.Style["font-family"] = "verdana"; 
                lname.Style["border"] = "solid 1px black";
                lname.Style["background-color"] = "beige";

Notice that the text box controls have been declared as protected members of the class to make them programmable within the class. Notice also the role of the base keyword that lets you invoke a method on the parent class.

Using code-behind does not mean that you have to renounce the <script> tag in the .ASPX file. Code-behind has two pleasant side effects. First, it allows you to isolate in a separate component all the boilerplate code for the page. Second, you can use different languages to build the page, and the languages used to write the code-behind file and the inline <script> tag can be different, as the following script and Figure 5-2 show:

<script language="VB" runat="server">
Public Sub Page_Load(s As Object, e As EventArgs)
    fname.Text = "Dino"
    lname.Text = "Esposito"
End Sub
Figure 5-2
This page was created using code-behind with the <script> tag.

By choosing the code-behind approach, you can control the base class of the page and also make it automatically inherit from previously compiled classes. This is the first step toward visual inheritance for ASP.NET pages.

Visual Inheritance for ASP.NET Pages

Let’s consider the following rather minimal Web page, which defines only a title and the code-behind information for Figure 5-3:

<%@ Page Language="C#" Inherits="BWSLib.MyBasePage"
     Src="MyBasePage.cs" %>
<title>Page Title</title>
<body bgcolor="ivory" style="font-family:arial;font-size:small">
Figure 5-3
In spite of an empty body, the page displays the output of some controls.

The output you see in Figure 5-3 is produced by controls that operate behind the curtain of the code-behind file. Let’s look at the source code:

public class MyBasePage : Page 
    public Label TopBarTitle;
    private Label lblURL;

    protected override void OnInit(EventArgs e) 
        // Use AddAt() to make sure these controls are added
        // at the top of the page. This simply serves the 
        // purposes of this demo and is not a general rule.
        Controls.AddAt(0, new LiteralControl("<h2>"));
        TopBarTitle = new Label();
        TopBarTitle.Text = "Top bar title";
        Controls.AddAt(1, TopBarTitle); 
        Controls.AddAt(2, new LiteralControl("</h2>"));

        Controls.AddAt(3, new LiteralControl("Current path: ")); 
        lblURL = new Label();
        lblURL.ForeColor = System.Drawing.Color.Blue;
        lblURL.Font.Size = FontUnit.Small;
        lblURL.Text = Request.Url.ToString();
        Controls.AddAt(4, lblURL);

        Controls.AddAt(5, new LiteralControl("<hr>"));

        // Call the page's OnLoad handler

The MyBasePage class has a public Label control representing the page’s top bar and a private Label control displaying the current URL. During the OnInit event, the class creates the tree of controls it needs. Next the class adds these child controls to the page’s Controls collection. Finally the parent page’s OnLoad event is called so that any code in the page’s Page_Load handler is run.

Deriving an .ASPX page from the MyBasePage class gives you a kind of visual inheritance because you automatically inherit the page structure built by the base class. Public properties are programmable. For example, the following code added to the previous .ASPX code produces Figure 5-4:

<script runat="server">
public void Page_Load(Object sender, EventArgs e)
    if (!Page.IsPostBack)
        TopBarTitle.Text = "This is my page";
Figure 5-4
This page structure was created with code inherited from the base class.