Code Reusability in ASP.NET

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="/books/2/368/1/html/2/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.

note

Visual Basic 6 uses the same approach to form development. In Visual Basic 6, a form is divided into two distinct parts: the graphical layout, and the code that interacts with controls. However, this logical distinction is lost when the form serializes to disk, because you always have a single FRM file with both code and layout information. The Visual Basic 6 integrated development environment (IDE) lets you see code and layout independently but does not allow different people to work on the same form at the same time.

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="/books/2/368/1/html/2/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.

caution

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="/books/2/368/1/html/2/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"  /> <br> <b><asp:label runat="server" Text="Last Name"/></b> <asp:textbox runat="server"  /> </form> </body> </html>

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) { base.OnLoad(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.

note

The base keyword is used in C# to access members of the base class from within a derived class. In Visual Basic .NET, you use the keyword MyBase.

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 </script>

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="/books/2/368/1/html/2/MyBasePage.cs" %> <html> <title>Page Title</title> <body bgcolor="ivory" style="font-family:arial;font-size:small"> </body> </html>

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 base.OnLoad(e); } }

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"; } } </script>

Figure 5-4

This page structure was created with code inherited from the base class.



Building Web Solutions with ASP. NET and ADO. NET
Building Web Solutions with ASP.Net and ADO.NET
ISBN: 0735615780
EAN: 2147483647
Year: 2002
Pages: 75
Authors: Dino Esposito

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net