How Code-Behind Files Are Connected to Pages in ASP.NET

Leave a Comment

Every .aspx page starts with a Page directive. This Page directive specifies the language for the page. and it also tells ASP.NET where to find the associated code (unless you’re using inline code, in which case the code is contained in the same file).

You can specify where to find the associated code in several ways. In older versions of ASP.NET, it was common to use the Src attribute to point to the source code file or the Inherits attribute to indicate a compiled class name. However, both of these options have their idiosyncrasies. For example, with the Inherits attribute, you’re forced to always pre-compile your code, which is tedious (and can cause problems in development teams, because the standard option is to compile every page into a single DLL assembly). But the real problem is that both approaches force you to declare every web control you want to use with a member variable. This adds a lot of boilerplate code.

You can solve the problem using a language feature called partial classes, which lets you split a single class into multiple source code files. Essentially, the model is the same as before, but the control declarations are shuffled into a separate file. You, the developer, never need to be distracted by this file - instead you can just access your web-page controls by name. Keen eyes will have spotted the word partial in the class declaration for your web-page code:
public partial class TestFormCodeRehind : System.Web.UI.Page
{ ...}

With this bit of infrastructure in place, the rest is easy. Your .aspx page uses the Inherits attribute to indicate the class you’re using, and the CodeFile attribute to indicate the file that contains your codebehind, as shown here:
<% Page Language=”C#” AutoEventWireup=”true” CodeFile=”TestFormCodeBehind.aspx.cs” Inherits= “TestFormCodeBehind" %>

Notice that Visual Studio uses a slightly unusual naming syntax for the source code file. It has the full name of the corresponding web page, complete with the .aspx extension, followed by the .cs extension at the end. This is just a matter of convention, and it avoids a problem if you happen to create two different code-behind file types (for example, a web page and a web service) with the same name.

0 comments:

Post a Comment