Code Separation

We saw earlier that files created with code separation now show in Visual Studio .NET "Whidbey" 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 public variables are required to reference the controls on a page.

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

Listing 2.1 Using Code Separationthe 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" id="Message" /> </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 Separationthe Code-Behind File
 Namespace ASP   Expands 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 Expands 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.



A First Look at ASP. NET v. 2.0 2003
A First Look at ASP. NET v. 2.0 2003
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 90

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