Home > Articles > Programming > ASP .NET

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020