Code Separation





Code Separation

We saw earlier that files created with code separation now show in Visual Studio 2005 as two files. In ASP.NET versions 1.0 and 1.1, the code-behind model allowed separation of code from content, and in ASP.NET 2.0 this model has been changed to simplify development. Instead of the content page inheriting from the code-behind page, we now specify which code-behind file is to be compiled with the content file. That may seem like just a change in semantics, but it's actually a more fundamental change, made at the Common Language Runtime (CLR) level.

Version 2.0 of the CLR provides support for partial classes, where the same class can span multiple files. This allows the code-separation page to be far simpler than in previous versions because it can be part of the same class as the content page, meaning no more protected variables are required to reference the controls on a page, and the Designer does not need to write code into the code-behind file.

The implementation of this is easy. Consider the page for Authors.aspx (Listing 2.1).

Listing 2.1. Using Code Separation—the ASP.NET Page

<%@ Page compileWith="Authors.aspx.vb"

         className="ASP.authors_aspx" %>



<form runat="server">



  <asp:Button runat="server" onClick="button_Click" />

  <asp:Label runat="server"  />



</form>


Because of partial classes, the code-separation file (Authors.aspx.vb) is simple, as shown in Listing 2.2.

Listing 2.2. Using Code Separation—the Code-Behind File

Namespace ASP



  Partial Class Authors_asp



    Sub button_Click(Sender As Object, E As EventArgs)

      Message.Text = "You pressed the button"

    End Sub



  End Class



End Namespace


Partial classes have introduced the new Partial keyword, indicating that this class is not self-contained and is part of the Authors_asp class. For the content page, the compileWith attribute defines the physical file containing the code to compile along with the content page, and the className attribute indicates the name (including the namespace) of the class. When the className attribute of the content file and the namespace and class of the code file match, code for both files is compiled into a single class.


     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows