- Creating Business Components
- Creating Multitiered Web Applications
- Using Code Behind
- Summary
Using Code Behind
Using components is an excellent method of moving your application logic outside your ASP.NET pages. However, as you have seen, components have one serious shortcoming. Because you cannot directly refer to the controls contained in an ASP.NET page from a component, you cannot move all your application logic out of the page.
In this section, you learn about a second method of dividing presentation content from code that remedies this deficiency. You learn how to take advantage of a feature of ASP.NET pages called code-behind.
You can use code-behind to cleanly divide an ASP.NET page into two files. One file contains the presentation content, and the second file, called the code-behind file, contains all the application logic.
Start with a page that has both its presentation content and application code jumbled together in one file. This page is shown in Listing 11.
Listing 11Jumble.aspx
<Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs ) lblMessage.Text = "Hello!" End Sub </Script> <html> <head><title>Jumble.aspx</title></head> <body> <form Runat="Server"> <asp:Button Text="Click Here!" OnClick="Button_Click" Runat="Server" /> <p> <asp:Label ID="lblMessage" Runat="Server" /> </form> </body> </html>
The page in Listing 11 contains one Button control and one Label control. When you click the button, the Button_Click subroutine executes and a message is assigned to the label.
Now, you can divide this page into separate presentation and code-behind files. The presentation file is simple; it just contains everything but the Button_Click subroutine. It also contains an additional page directive at the top of the file.
Listing 12Presentation.aspx
<%@ Page Inherits="myCodeBehind" src="myCodeBehind.vb" %> <html> <head><title>Presentation.aspx</title></head> <body> <form Runat="Server"> <asp:Button Text="Click Here!" OnClick="Button_Click" Runat="Server" /> <p> <asp:Label ID="lblMessage" Runat="Server" /> </form> </body> </html>
The code behind file, contained in Listing 13, is a little more complicated. It consists of an uncompiled Visual Basic class file.
Listing 13myCodeBehind.vb
Imports System Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.UI.HtmlControls Public Class myCodeBehind Inherits Page Protected WithEvents lblMessage As Label Sub Button_Click( s As Object, e As EventArgs ) lblMessage.Text = "Hello!" End Sub End Class
That's it. That's all you need to do to cleanly divide a page into separate files for presentation content and application logic. If you save the Presentation.aspx and myCodeBehind.vb files anywhere on your Web server, you can immediately open the Presentation.aspx file in a Web browser, and the page will work as expected.
Notice that you do not even have to compile the code behind file. The Visual Basic class contained in the code behind file is compiled automatically when you request the Presentation.aspx page.
How Code Behind Really Works
If you look closely at the Visual Basic class declared in the code-behind file in the preceding section, you notice that the myCodeBehind class inherits from the Page class. The class definition for myCodeBehind begins with the following statement:
Inherits Page
When you create a code-behind file, you are actually creating an instance of an ASP.NET page. You're explicitly building a new ASP.NET page in a class file by inheriting from the Page class.
Code behind pages use an additional level of inheritance. The page used for the presentation content in the preceding section, Presentation.aspx, inherits from the code-behind file. The first line of Presentation.aspx is as follows:
<%@ page inherits="myCodeBehind" src="myCodeBehind.vb" %>
The presentation page inherits all the properties, methods, and events of the code-behind file. When you click the button, the Button_Click subroutine executes because the presentation page is inherited from a class that contains this subroutine.
So, the code-behind file inherits from the Page class, and the presentation file inherits from the code-behind file. Because this hierarchy of inheritance exists, all the properties, methods, and events of the Page class are available in the code-behind file, and all the properties, methods, and events in the code-behind file are available to the presentation file.
When using code-behind files, you must be careful to declare an instance of each control used in the presentation file within the code-behind file. For example, in the code-behind file, you refer to the lblMessage control in the Button_Click subroutine. So, you have to explicitly declare the control in the code-behind file like this:
Protected WithEvents lblMessage As Label
If you neglect to include this declaration, you would receive the error The name 'lblMessage' is not declared when attempting to open the presentation page in a browser.
Compiling Code Behind Files
You don't need to compile a code-behind file. The class file contained in a code-behind file is compiled automatically when you request the presentation page. If you prefer, however, there is nothing to prevent you from compiling it. For example, to compile a code behind file named CodeBehind.vb, execute the following statement from a DOS prompt in the same directory as your code behind file:
vbc /t:library /r:system.dll,system.web.dll CodeBehind.vb
This statement compiles a code behind file named CodeBehind.vb into a file named CodeBehind.dll. The /t option indicates that a DLL file should be created. The /r option references the system.dll assembly and system.web.dll assembly. (All the Web control classes inhabit this assembly.)
After you compile the code-behind file into CodeBehind.dll, you need to move this file to your application's /BIN directory.
Finally, modify the page directive on the presentation page. Change the page directive from
<%@ Page Inherits="CodeBehind" src="CodeBehind.vb" %>
to
<%@ page inherits="CodeBehind" %>
You no longer need the src attribute because the compiled code-behind file is located in the /BIN directory. The compiled classes in the /BIN directory are automatically available to use in all the ASP.NET pages in an application.
Inheriting Multiple Pages from a Code Behind File
You can inherit multiple presentation pages from the same code-behind file. In fact, if you really want to, you could inherit all the pages in your Web site from a single code-behind file.
Why is this capability useful? Imagine that you have a set of functions and subroutines that you need to call in almost every page. You can place the functions and subroutines in your code-behind file, and they are immediately available in any page that inherits from the code-behind file.
The code-behind file in Listing 14, for example, has one subroutine and one function. The subroutine is the standard Page_Load subroutine that executes whenever a page is first loaded. The utility function named HeaderMessage() returns the current date.
Listing 14CodeBehindMultiple.vb
Imports System Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.UI.HtmlControls Public Class CodeBehindMultiple Inherits Page Protected WithEvents lblHeader As Label Overridable Sub Page_Load lblHeader.Text = HeaderMessage() End Sub Function HeaderMessage() As String Dim strMessage As String strMessage = "Welcome to this Web site!<br>" strMessage &= "The current date is " strMessage &= DateTime.Now.ToString( "D" ) Return strMessage End Function End Class
Any page that derives from the code-behind file in Listing 14 inherits both the Page_Load subroutine and HeaderMessage() function. For example, the presentation page in Listing 15 automatically uses the Page_Load subroutine from the code-behind file.
Listing 15PresentationMultiple1.aspx
<%@ Page Inherits="CodeBehindMultiple" src="CodeBehindMultiple.vb" %> <html> <head><title>PresentationMultiple1.aspx</title></head> <body> <form Runat="Server"> <asp:Label ID="lblHeader" Runat="Server" /> <h2>Page 1</h2> </form> </body> </html>
When you open the page contained in Listing 15, the Page_Load subroutine from the code behind file executes, and the header Label is assigned the text from the HeaderText() function.
Now, imagine that you want to use the Page_Load subroutine declared in the code behind file in some pages that inherit from the code behind file but not others. Because you declared the Page_Load subroutine as Overridable, you can override it in a presentation page.
The page in Listing 16, for example, overrides the Page_Load subroutine with its own Page_Load subroutine and displays a custom message in the header Label.
Listing 16PresentationMultiple2.aspx
<%@ page Inherits="CodeBehindMultiple" src="CodeBehindMultiple.vb" %> <Script Runat="Server"> Overrides Sub Page_Load lblHeader.Text = "Who cares about the current date?" End Sub </Script> <html> <head><title>PresentationMultiple2.aspx</title></head> <body> <form Runat="Server"> <asp:Label ID="lblHeader" Runat="Server" /> <h2>Page 2</h2> </form> </body> </html>
Notice that the Page_Load subroutine uses the Overrides modifier, which overrides the Page_Load subroutine declared in the code-behind file. You can set it up this way because the Page_Load subroutine was declared with the Overridable modifier.
Now, try one last example. Imagine that you want to create a page that executes the Page_Load subroutine in the code-behind file but also executes a Page_Load subroutine of its own. You can extend the subroutine in the code-behind file within a presentation file by overriding the original subroutine and calling the original subroutine in the new subroutine. In other words, you can extend the code-behind subroutine in your presentation file.
The presentation page in Listing 17 illustrates how you would do so.
Listing 17PresentationMultiple3.aspx
<%@ page inherits="CodeBehindMultiple" src="CodeBehindMultiple.vb" %> <Script Runat="Server"> Overrides Sub Page_Load myBase.Page_Load lblHeader.Text &= "<br>And the current time is " lblHeader.Text &= Now.ToString( "t" ) End Sub </Script> <html> <head><title>PresentationMultiple3.aspx.aspx</title></head> <body> <form Runat="Server"> <asp:Label ID="lblHeader" Runat="Server" /> <h2>Page 3</h2> </form> </body> </html>
In Listing 17, the Page_Load subroutine overrides the Page_Load subroutine from the code-behind file. However, notice this statement:
myBase.Page_Load
This statement invokes the Page_Load subroutine in the code behind file. The Visual Basic myBase keyword refers to the base class that the current class is derived from. Therefore, when the page contained in Listing 17 is opened in a browser, the Page_Load subroutines in both the code behind file and presentation file are executed. The page in Figure 5 is displayed.
Figure 5 Extending a code-behind subroutine.
Compiling a Complete ASP.NET Page
In this article, you have examined various methods of moving the application logic out of an ASP.NET page and placing it in a separate file. In this section, I want to discuss an extreme case. How would you go about compiling all of an ASP.NET page, including both the presentation content and application code?
You might want to compile a complete page in several circumstances. For example, imagine that you have developed an e-Commerce Web site, and you want to sell the site to multiple clients. When you distribute the site, you might not want the clients to be able to easily view the source code. If you compile all the pages in your application, all the Visual Basic source code is hidden from view.
You can compile an ASP.NET page by placing all its contents into a code-behind file. In the code-behind file, you must explicitly declare all the controls and all the static content that appears in the page.
The code-behind file in Listing 18 contains a complete ASP.NET page in a Visual Basic class.
Listing 18myPage.vb
Imports System Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.UI.HtmlControls Public Class myPage Inherits Page Dim txtTextBox As New TextBox Dim lblLabel As New Label Protected Overrides Sub CreateChildControls ' Add Opening HTML Tags Dim strOpenHTML As String strOpenHTML = "<html><head><title>My Page</title></head>" strOpenHTML &= "<body>Enter some text:" Controls.Add( New LiteralControl( strOpenHTML ) ) ' Add HTMLForm Tag Dim frmForm As New HTMLForm frmForm.ID = "myForm" Controls.Add( frmForm ) ' Add a TextBox txtTextBox.ID = "myTextBox" frmForm.Controls.Add( txtTextBox ) ' Add a Button Dim btnButton As New Button btnButton.Text = "Click Here!" AddHandler btnButton.Click, AddressOf Button_Click frmForm.Controls.Add( btnButton ) ' Add Page Break frmForm.Controls.Add( New LiteralControl( "<p>" ) ) ' Add a Label lblLabel.ID = "myLabel" frmForm.Controls.Add( lblLabel ) ' Add Closing HTML Tags Dim strCloseHTML As String strCloseHTML = "</form></body></html>" Controls.Add( New LiteralControl( strCloseHTML ) ) End Sub Sub Button_Click( s As Object, e As EventArgs ) lblLabel.Text = txtTextBox.Text End Sub End Class
The bulk of the code in Listing 18 is contained in a subroutine called CreateChildControls. In this subroutine, you create each of the controls that you want to appear in your ASP.NET page.
To add static content to the page, you use the LiteralControl control. For example, you use LiteralControl to create the opening HTML tags at the beginning of the CreateChildControls subroutine and the closing HTML tags at the end of the subroutine.
You also add all the Web controls to the page within the CreateChildControls subroutine. First, you add an HTMLForm control to the page's Controls collection. Next, you add TextBox, Button, and Label controls to the HTMLForm's Controls collection.
Finally, your page class contains a subroutine named Button_Click. This subroutine is executed when you click the button. The Button_Click subroutine assigns whatever text was entered into the TextBox control to the Label control.
To wire up the Button_Click control to the Button control, you use the following statement:
AddHandler btnButton.Click, AddressOf Button_Click
This statement adds an event handler to the Click event of the Button control. It associates the Button_Click subroutine with the Click event. So, whenever the button is clicked, the Button_Click subroutine is executed.
After you create the page class in Listing 18, you can compile it by using the following statement:
vbc /t:library /r:system.dll,system.web.dll myPage.vb
After the page is compiled, you need to move it to your application's /BIN directory.
Finally, to request the compiled page in a Web browser, you have to create one additional file. This file is contained in Listing 19.
Listing 19ShowMyPage.aspx
<%@ Page inherits="myPage" %>
As you can see, the ShowMyPage.aspx file contains a single line; it's a page directive indicating that the current page should inherit from the myPage class. When you open ShowMyPage.aspx in a Web browser, the ASP.NET page created in the code behind file is displayed.