In the world of increasingly complex Web applications, it's often difficult to separate the different parts of the development process. Writing Web applications is hard enough without worrying about how to make them look good and stay maintainable over the years . Some companies have designers who create the look and feel of the site, allowing the programmers to concentrate on the coding. With the traditional ASP model, this is hard to achieve, as code and content are often intermixed.
The way to solve this problem in ASP.NET is by using Code-Behind, where the content (HTML and server controls) are in one file, and the server-side code in another. Not only does this allow different people to work on the same page at once, but it also enables either part to be redesigned (as long as the controls still stay the same) without affecting the other.
The code-behind model is no different in action to pages where the code is inline. Remember that an ASP.NET page and its associated files are compiled into an executable object. This object is essentially (as far as performance and use go) the same as any other page, allowing easier development with the same effect.
The approach to use for code may depend on the tool used to create ASP.NET applications. For this book, most of the samples will show code inline, simply because it's easier to show, as well as being more convenient when using text editors such as Notepad.
Tools such as Visual Studio .NET take the opposite approach, using the code-behind model as default. One reason is that it allows a standard HTML designer to be used for designing the look and feel of the page, and a code editor to be used for the actual code. This gives the user the familiar feel (comparable to the Visual Basic 6 environment) of design and code windows .
Another reason is that Microsoft has taken the view that third parties may want to use write designers or code editors that integrate with .NET. The code-behind approach allows any HTML designer and any editor to be used (as long as it doesn't change ASP.NET controls).
The principle of code-behind is to create a class for the code, and inherit this class from the ASP.NET Page object. This gives your class access to the page intrinsics , and allows it to interact with the postback architecture. You can then create the ASP.NET page and use a page directive to inherit from the newly created class.
There are some rules that you should follow to create the code-behind class, the first of which is to reference the required namespaces. At a minimum you need to reference System and System.Web.UI , although others may be required. For example, to reference controls on the page and to define the control types, you should reference System.Web.UI.WebControls . Also include any other required namespaces, such as System.Data.SqlClient for accessing SQL Server.
The second rule is create a class that inherits from the Page object (this is why the System.Web.UI namespace is needed). Within this class, you should declare public instances of ASP.NET server controls that are on the Web page, using the same name for the variables that the Web Control has. This provides a link between the code-behind class and the actual server controls (there are other ways to do this, but this method is simplest). Within this class, create event procedures, methods , and properties, just as with any class. The events can be event procedures named on server controls in the web page.
For example, consider the simple select list with Shipping Methods shown earlier in the chapter. The following code samples show the code-behind class. With the exception of the additions required for the code-behind model, the code is exactly the same as the code inline samples.
Imports System Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Data Imports System.Data.SqlClient Public Class ShipMethodClass Inherits Page ' public variables to match the server controls Public ShipMethod As DropDownList Public YouSelected As Label Public PlaceOrder As Button Sub Page_Load(Source As Object, E As EventArgs) If Not Page.IsPostBack Then Dim myConnection As SqlConnection Dim myCommand As SqlCommand Dim myReader As SqlDataReader Dim SQL As String Dim ConnStr As String SQL = "SELECT * FROM Shippers" ConnStr = "server=localhost;uid=sa;pwd=;database=Northwind" myConnection = New SqlConnection(ConnStr) myConnection.Open() myCommand = New SqlCommand(SQL, myConnection) myReader = myCommand.ExecuteReader() ShipMethod.DataTextField = "CompanyName" ShipMethod.DataSource = myReader ShipMethod.DataBind() End If End Sub Sub PlaceOrder_click(Source As Object, E As EventArgs) YouSelected.Text = "Your order will be delivered via " & _ ShipMethod.SelectedItem.Text End Sub End Class
using System; using System.Data; using System.Data.SqlClient; using System.Web.UI; using System.Web.UI.WebControls; public class ShipMethodClass : Page { // public variables to match the server controls public DropDownList ShipMethod; public Label YouSelected; public Button PlaceOrder; public void Page_Load(Object Source, EventArgs E) { if (!Page.IsPostBack) { SqlConnection myConnection; SqlCommand myCommand; SqlDataReader myReader; String SQL; String ConnStr; SQL = "select * from Shippers"; ConnStr = "server=localhost;uid=sa;pwd=;database=Northwind"; myConnection = new SqlConnection(ConnStr); myConnection.Open(); myCommand = new SqlCommand(SQL, myConnection); myReader = myCommand.ExecuteReader(); ShipMethod.DataTextField = "CompanyName"; ShipMethod.DataSource = myReader; ShipMethod.DataBind(); } } public void PlaceOrder_Click(Object Source, EventArgs E) { YouSelected.Text = "Your order will be delivered via " + ShipMethod.SelectedItem.Text; } }
To connect the class file containing the code implementation to your ASP.NET page, add an Inherits attribute to the <%@Page ... %> directive, and specify the location of the 'Code-Behind' file:
<%@Page Inherits=" class_name " Src=" path_to_class_file " %>
For example, to inherit from a Visual Basic .NET class named ShipMethodClass that is implemented in a file named ShipMethodClass.vb in the same directory as the page, you would use:
<%@Page Inherits="ShipMethodClass" Src="ShipMethodClass.vb" %>
Important | Use the correct file extension for your class files “ .vb for Visual Basic files, .js for JScript files, .cs for C# files and .cpp for C++ files. This ensures that they are passed to the correct compiler when the page is first executed. |
An alternative form of this directive allows the Src attribute to be omitted:
<%@ Page Inherits="ShipMethodClass" %>
In this case ASP.NET will assume that the class is pre-compiled, and in the bin directory of the application.