Home > Articles > Programming > ASP .NET

  • Print
  • + Share This
This chapter is from the book

Separating Presentation from Code Using Code Behind

Code in ASP.old was often difficult to maintain because it was interspersed with HTML markup. Even when using a visual development tool such as Visual InterDev or Dreamweaver UltraDev, it could be difficult and time consuming to track down a chunk of ASP code that needed to be debugged.

The solution to this problem is a tactic that developers on many platforms typically use: separating logic (the code that you write) from presentation (the way the data appears). By separating logic from presentation, you can be assured that all the code is located in the same place, organized the way you want, and easily accessible. Separating logic from presentation also minimizes the possibility that you'll generate new bugs in the presentation code as you debug the core logic of the application.

One tactic for separating code from presentation in ASP.NET is code behind. Code behind is a feature that enables you to take most of or all the code out of an ASP.NET page and place it in a separate file. The code is processed normally; the only difference is where the code is located.

Visual Basic actually introduced the concept of code behind. The idea was that the code that dealt with a particular object was in a different layer "behind" the object. Of course, this was only one way to describe it. In reality, code behind was just a separate source file for each form that encapsulated the code related to that form. The code in the file was actually tightly coupled with the form.

ASP.NET has this same concept with a slight twist. If you write a page as shown in Listing 3.7, behind the scenes ASP.NET creates code behind for you—invisibly in the background. A class is created that inherits from System.Web.Page and includes a Dim statement for each runat=server control in your page. This is done by default to enable you to continue programming using the simple model provided in ASP.old.

Alternatively, you can create this class yourself and derive the page from it. This separates the code from the layout of the page. This separation is potentially a huge benefit. In my previous life I worked with a company whose standard development process went something like this: A business process owner would decide that some feature should be Web enabled. The owner would come to a designer with, at best, a couple of sketches of what the Web pages needed to implement this feature should look like. The owner would then work with the designer to create a series of HTML pages that represented the feature. These pages would then be handed off to a developer to "activate" them. The developer would go through the pages, adding the code to actually make the feature work. When the developer was done, the feature was then shown to the business process owner. Inevitably, the owner would realize that several features had been missed and/or additional features were needed.... So the process would start over again. The designer would take the completed pages and start moving the HTML around to meet the needs of the change requests. After the pages were again looking good, the designer would hand off to the developer. The developer would open up the pages and throw his or her hands up in despair. In the process of reformatting and rearranging the HTML, the designer inevitably would have scrambled the ASP.old code that had lived intermixed with the HTML. In many instances, it was easier for the developer to just rip the old code out and re-add it via copy/paste from the first version. This iterative process could continue for dozens of rounds, depending on the complexity of the feature.

I suspect my previous company and I were not the only ones frequently faced with this issue. It begs for a new model that allows the separation of the layout and formatting from the code that operates on it. ASP.NET is not Microsoft's first attempt at this concept. It was tried, as part of Web Classes in Visual Basic 6.0 but was not very successful. I predict that ASP.NET will be a much more successful implementation.

The way that code behind in ASP.NET works is that you create a class that inherits from System.Web.UI.Page. This is the base class for a page.

Note

A complete reference to the Page object can be found at the end of this chapter.

The .aspx page then inherits from the class you create. This inheritance is accomplished via the @Page directive that is discussed in further detail in this chapter. The @Page directive Inherits attribute enables you to indicate from which class the page should inherit.

The Src attribute enables you to indicate from which file the source code should be dynamically compiled. This last attribute is not required if the class has already been compiled and is in the Global Assembly Cache. Alternatively, under the directory the page is in, you can create a special directory called /bin. This directory is one of the first places ASP.NET looks for already compiled code. If the code has not already been compiled, the file reference by the Src attribute is compiled and looked at for the class specified in the Inherits attribute. Listing 3.8 shows the aspx page for the sample we have been looking at previously. Note that no code is in this page, just HTML markup.

Listing 3.8 SimplePage3.aspx Using Code Behind; This Is the .aspx Page.

<% @Page src="simplepage3.aspx.vb" Inherits="SimplePage" %>
<html>
<head>
  <title>SimplePage3.aspx</title>
</head>

<script language="VB" runat=server>
</script>

<body>
  <form id="WebForm1" method="post" runat="server">
    <p>
    <table border=0>
      <tr>
        <td>Name:</td>
        <td><asp:textbox id=txtName runat=server /></td>
        <td><asp:button id=Button1 Text="Send" runat=server /></td>
      </tr> 
      <tr>
        <td valign=top>Hobby:</td>
        <td>
          <select id=lbHobbies Multiple runat=server>
            <option Value="Ski">Ski</option>
            <option Value="Bike">Bike</option>
            <option Value="Swim">Swim</option>
          </select>
        </td>
        <td>&nbsp;</td>
      </tr>
    </table>
    </p>
    <asp:label id=lblOutput runat=server />
  </form>
</body>
</html>

Also note the @Page tag that indicates the code for this page is in a file called SimplePage3.aspx.vb. The class that implements the functionality for this page is called SimplePage. Listing 3.9 shows SimplePage3.aspx.vb.

Listing 3.9 Simplepage3.aspx.vb Is the Code-Behind File for SimplePage3.aspx

public class SimplePage
  Inherits System.Web.UI.Page

  Protected WithEvents Button1 As System.Web.UI.WebControls.Button
  Protected txtName as System.Web.UI.WebControls.TextBox
  Protected lblOutput as System.Web.UI.WebControls.Label
  Protected lbHobbies as System.Web.UI.HtmlControls.HtmlSelect

  private sub Button1_Click(ByVal sender as System.Object, _
     ByVal e as System.EventArgs) Handles Button1.Click
    Dim strTemp as String
    Dim iCount as Integer
  
    ' Build up the output
    strTemp = "Name:" + txtName.Text + "<BR>Hobbies: " 
    for iCount = 0 to lbHobbies.Items.Count - 1
      if lbHobbies.Items(iCount).Selected Then
        strTemp = strTemp + lbHobbies.Items(iCount).Text + ", "
      end if
    Next
    
    ' Place it into the label that was waiting for it
    lblOutput.Text = strTemp
  End Sub
End Class

This looks very similar to the previous example, except that no markup is in the page! It is strictly code. One cool feature is that by altering the Inherits attribute, you can tie more than one aspx page to the same code-behind file.

Code behind gives you an additional way to wire up events. It's best not to make the HTML markup know any more than it needs to about the code. Using the approach shown earlier to wire up events, you're required to know the name of the event procedure in the code behind. An alternative is to use WithEvents. In Listing 3.9, you will notice that Button1 is defined WithEvents. Furthermore, the event handler Button1_Click has a Handles Button1.Click on the end. This is an alternative way to wire up the event handlers for ASP.NET with code behind. With this technique, the HTML markup doesn't have to know anything about the code-behind class.

  • + Share This
  • 🔖 Save To Your Account