Buy this Book
Print Book $44.99 PDF $30.99 Read it Now! Print Book £27.99
Add to UK Cart
Reprint Licensing

Learning ASP.NET 2.0 with AJAX
Learning ASP.NET 2.0 with AJAX A Practical Hands-on Guide

By Jesse Liberty, Dan Hurwitz, Brian MacDonald
Book Price: $44.99 USD
£27.99 GBP
PDF Price: $30.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Getting Started
Learning ASP.NET 2.0 with Ajax will teach you everything you need to know to build professional quality web applications using Microsoft's latest technology, including ASP.NET 2.0 and AJAX. ASP.NET is Microsoft's tool for creating dynamic, interactive web pages and applications. Using plain vanilla HTML, you can make a web page that has some great content, but it's static. The content doesn't change, no matter what the user does. You can even use Cascading Style Sheets (CSS) to make it the most visually impressive thing on the Web, but if what you really need is for users to be able to leave comments, or browse your inventory, or buy things from you, then HTML alone won't get it done.
That's where ASP.NET 2.0 comes in. Within these chapters, you'll find out how to do all the great tricks that you see on the most popular commercial web sites. Order forms? We've got that. Interact with a database? You'll do that too. Dynamic navigation tools? It's in here. Personalized appearance that the user can customize? No problem.
The best part is, you'll do it all with minimal coding. You can make ASP.NET pages in your favorite text editor if you want, but that's a bit like using a hammer and chisel to write the Great American Novel. If you use Visual Studio 2005, or its free counterpart, Visual Web Developer, adding features to your page is as simple as dragging and dropping. The tools generate most of the code for you. If you're an old-school type who cringes at the idea of letting someone else write your code, it's all still there, and you can tweak it to your heart's content. Consider this, though: would you rather spend your time writing the code for another radio button list, or figuring out what to do with the data that you gather using it? In short, the tools do the tedious chores for you, so you can get to the good stuff.
On top of all this, you can enhance your ASP.NET 2.0 site with AJAX, which is more than just résumé enhancement; it's a genuine improvement in the user experience. When a user is browsing your product catalog, and she clicks on one of your thumbnail images to view the product's details in another panel, she simply expects it to
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Hello World
One of the most difficult problems in beginning any programming technology is the "bootstrap" problem. That is, writing your first program requires using techniques that you haven't learned yet, but learning those techniques in a vacuum is not only boring, but to some degree pointless because there's no context, and thus no way to integrate that which you learned.
The traditional solution to this dilemma is to create the canonical "Hello World" program. Our Hello World web site will allow us to demonstrate many useful aspects of ASP.NET without overwhelming you with detail. We promise we will explain every aspect of this web site in detail, as we go along.
According to Wikipedia (), the tradition of a Hello World program dates back to a 1974 Bell Laboratories memorandum by Brian Kernighan.
This introductory web site will have only a Button and a Label control. Initially the Label will display the text "Label." When the user clicks the Button, the Label text becomes "Hello World." Very cool, eh? You can see the finished product in , after the user clicked the button.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a New Web Site
To get started, open the Integrated Development Environment (IDE), which for these purposes is either Visual Web Developer or Visual Studio. (Throughout this book, we will use the acronym IDE for both, specifically using VS or VWD only where they are different.)
Figure : This is what the HelloWorld web site will look like after the user clicks the Button.
To create a new web site, click on the menu item File → New Web Site…, or alternatively, use the Create: Web Site… link on the Start Page. Either way, you should see the New Web Site dialog, like the one shown in .
In this book, we will be using Visual Basic as our default language, although it is the profound belief of the authors that Visual Basic and C# are really a single language, just with slightly different syntax.
We will be showing many of our screen shots from Visual Web Developer, because it is freely available from Microsoft, however, anything that can be done in Visual Web developer can also be done in Visual Studio.
Take another look at , and we'll examine it in some detail. In the upper part of the window, you are offered various Visual Studio templates (though yours may vary). Select the ASP.NET Web Site template, because that is the kind of site that you are going to create (shown circled in this figure).
In the Location drop-down box at the bottom of the dialog box, select File System (the other options are HTTP or FTP; we'll explain this selection later in the next section).
The Location drop-down in covers up another drop-down in which we have set the language to Visual Basic (rather than to Visual C# or Visual J#). Finally, you need to specify where on your disk you would like this web site to be placed—in this case, in the LearnASP directory on the C drive.
Figure : To create a new web site, open the IDE, and click on Menu → New Web Site to open the New Web Site dialog box. The Templates and My Templates panels show you the types of sites supported by your version of Visual Studio.
The name of the new web site will be Hello World (with no space character). The site will be fully contained in a subdirectory named
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating HelloWorld
After you've named your new web application and chosen a place to host it, the IDE will look more or less like . This is where you do the real work of putting your site together.
Which exact windows you see and how they are presented may be influenced by options you've chosen. In your IDE, you can always open new windows from either the View or Window menu and you can undock, move, and redock the various windows using the mouse and the on-screen docking indicators.
Figure : Initial IDE screen for HelloWorld. This is what you'll see after you've named your web site, chosen a language, and created a directory for it.
In , you see the main window, which shows the page markup: HTML plus ASP.NET declarations and controls. Also note the two tabs at the bottom of this pane, labeled Design and Source. You'll be using these two tabs a lot as you create your pages.
To start, click on the Design tab. When you click this tab, the middle window of your IDE becomes the design surface. On the design surface, you can drag and drop items such as buttons, text fields, labels, and so on from the Toolbox, which you'll see in a moment, where they automatically become part of your application. Each item that you can drag onto the design surface is called a control. You'll be reading more about controls in and throughout this book.
Next, click on the Source tab. This view allows you to see the same controls, but displayed as HTML and ASP.NET markup. When you drag a control onto the design surface, the IDE automatically adds the appropriate markup to make that control part of the page. You can view and adjust that markup from the Source tab and even drag controls from the Toolbox directly onto the Source view. As you switch back and forth between Source and Design view, they will remain consistent with one another as they are two views of the same information.
Many working programmers and even Microsoft itself will refer to markup as source code. Other programmers draw a distinction between markup (HTML, ASP.NET controls, XML, etc.) on the one hand, and source code (C#, VB.NET, JavaScript) on the other. This can, and does cause confusion, and all ASP.NET programmers learn to differentiate as best we can by context. The Source tab shows markup or HTML source code. The "code-behind" page, discussed below, shows C# or VB.NET source code. Not a perfect naming system, but there you have it. In practice, markup and ASP.NET source code have become synonymous.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Making the HelloWorld Web Site Interactive
You've created your web page, but it doesn't do much of anything right now. To make your page come alive, you need to add some controls to it. Everything that you'll find in the Toolbox is a control, and you can add controls to your pages simply by dragging them onto either the design surface or into the Source view.
For this first program, you'll add a button and a label to your page, making it look like what you saw back in . Follow these steps:
  1. Click the Design tab at the bottom of the main window to ensure that you are in Design view.
  2. If the Toolbox window is not already pinned in place, click on the pushpin icon in its title bar to pin it in place.
  3. If the Standard category of the Toolbox is not expanded, click on the plus symbol and expand it. You should be able to see a number of basic controls listed in the Toolbox, such as "Label," "TextBox," and "Button."
  4. Click on a Button control in the Toolbox, and drag it onto the design surface.
  5. Click on a Label control in the Toolbox, and drag that onto the design surface next to the button.
At this point, your IDE should appear similar to .
Figure : After you've added the button and label to your HelloWorld application, the design view should look like this.
This is a good time to stop and run your program, to see what it does so far. There are three ways to do so:
  • Click on the menu item Debug → Start Debugging
  • Press the F5 keyboard shortcut
  • Click on the Start Debugging icon () on the toolbar
Because this is the first time you've run the program, the IDE will detect that your web.config file is not set to allow debugging and will offer to make that adjustment for you, as shown in .
Figure : You'll see this Debugging Not Enabled dialog box the first time you run your application. Just select the first option and click OK to keep going.
It's not important to know what a web.config file is right now, but we'll explain it later. For now, click OK to allow the IDE to modify the configuration file.
After clicking OK, your application begins, your default browser opens, and your button is displayed, as shown in .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What You Just Did
When you follow step-by-step instructions as if following a recipe, it's easy to lose sight of what you've done. Here's a quick review:
  • You created a new web site on your file system.
  • You dragged a Button and a Label into the design surface.
  • You double clicked on the Button to create an event handler.
  • In the event handler, you assigned "Hello World" to The Text property for the Label control.
  • You ran your application and clicked on the Button, causing the page to be sent back to the server where the event handler code was evaluated. The text "Hello World" was assigned to the Label and the page was sent back to the browser.
Congratulations! You've just built your first bona fide web page—and it's interactive, too. Pretty easy, isn't it? You've seen how to use the IDE, you've worked in Design view and in the code-behind file, and most important, you saw how to create a page that actually responds to user input.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
  • ASP.NET 2.0 lets you create interactive web pages and applications. With dynamic pages, you can interact with your users and create a richer experience for them.
  • Visual Studio 2005, or the free Visual Web Developer, supplies the tools that make creating a web page as easy as dragging and dropping, minimizing the code you need to manually write.
  • AJAX is a set of tools that you can use to make the user's experience more seamless, by reducing the number of page flickers caused by the entire page posting back.
  • You can create a new web site, or open an existing one from the Start Page in Visual Web Developer or Visual Studio.
  • In ASP.NET, you can store your entire web site within a single directory, which in this book will always be on your local hard drive, but you can also store them at a remote location and serve them using IIS.
  • The main window of the IDE has two views: Design and Source. Design view allows you to see the visual design of your web page; Source view shows the HTML and ASP.NET markup instead. You can switch between the two views on the fly.
  • The items that you add to your web page are called controls. Controls are stored in the Toolbox, which by default appears on the left side of the IDE. You add controls to the page simply by dragging them from the Toolbox onto the appropriate spot on the page, in either Design view or Source view.
  • The Solution Explorer, located on the right side of the IDE, displays the files in your web site. Below the Solution Explorer is the Properties window, which lets you adjust the properties of any control you select. On a separate tab is the Database Explorer for access to the databases and servers that support your web site.
  • You can run your application by clicking Debug → Start Debugging from the menu, pressing F5, or clicking the Start Debugging button.
  • Web applications are event-driven, meaning that the controls raise events, which are handled by code blocks called event handlers.
  • When you double-click on a control, you're automatically taken to the codebehind file, where the IDE will create a handler for the control's default event.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
BRAIN BUILDER
  1. How do you create a new web site in the IDE?
  2. What are the two views of your page that you can use in the IDE?
  3. What's the name for the settings that are specific to each control?
  4. Where in the IDE will you find the controls that you can place on your page?
  5. How do you run your application?
  6. What event is raised when you click on the Button control?
  7. Where is the code for the event handler located?
  8. What's one way to access the default event handler's code?
  9. What property of the Label control do you use to set its content?
  10. Every ASP.NET web site has at least one web page. What is the extension for the file that contains this page?
Exercise1-1.This is your first exercise, so we'll take it easy on you—you'll make some changes to HelloWorld. Open the example again. Recall there are a few ways to do this:
  • Select File → Open Web Site.
  • Click the Start Page tab at the top of the main window to display the Start Page, and click the Open Web Site link, or select it from the Recent Projects list, if it's there (and it should be, if you've just finished this chapter).
With the file open, select the code-behind file, either from the tab at the top of the window, or in Solution Explorer. Go to the Clickevent handler, and change the "Hello World" text to a message of support for your favorite sports team (or band, or movie, or whatever you like).
Now switch back to the .aspx file. Select the label control, and check out the Properties window. There's more here than just setting the text, as you've seen. Go to the Appearance section of the Properties, and play around with them to your liking. Click the + sign next to the Font property, and you'll find lots of options with which you're probably familiar. Try changing the font, the text size, and the color. You can also play with the border of the label too. Note that if you change the Text property here, you're changing the initial text of the label. After you've kicked the tires a bit, run your application to see how it looks. You can see an example in , although this is the affiliation of only one of the authors.
Figure : The results of Exercise 1-1, for at least one of the authors. Your page may look different, depending on your sports loyalties.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Building Web Applications
You've built your first web site, and you've gotten your feet wet, which is great. But so far, you've only used two controls: Label and Button. You've seen the Toolbox in the IDE, and it's stuffed with controls just waiting for you to experiment with. That's exactly what you're going to do in this chapter. You'll build a functional order form for a fictional business, even though you won't do anything just yet with the data your form will collect. You'll get to try out many of the basic controls in both Design view and Source view, you'll learn about web site fundamentals and selection controls and their collections of items, and you'll see how to display the results retrieved by one control in another control somewhere else on the page.
The difference between a web page that simply displays information and a web application that interacts with your user is the application's ability to gather data from the user, process it on the server, and take action accordingly. The core of a web application is the page and its interactive controls. This part of the chapter will introduce the web page and the types of controls that you'll use throughout the remainder of this book, and throughout your ASP.NET programming career. We will also introduce the mindset that will move your applications from being a "brochure" that displays information, into an interactive application delivered over the Web.
Every ASP.NET web site consists of at least one web page stored in a single file with the extension .aspx. There is usually more than one file, as you will see as we go along. The .aspx file is called a content file. Some developers call it the markup file, which makes sense when you remember that HTML stands for HyperText Markup Language.
The contents of the page itself are comprised of "server controls" and "normal" HTML. Server controls are simply controls with code that runs on the server. Normal HTML is sent to the browser "as is." For technical details on how these pages are processed by the web server, see the sidebar below, "How Pages Are Processed on the Server."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Mastering Web Site Fundamentals
The difference between a web page that simply displays information and a web application that interacts with your user is the application's ability to gather data from the user, process it on the server, and take action accordingly. The core of a web application is the page and its interactive controls. This part of the chapter will introduce the web page and the types of controls that you'll use throughout the remainder of this book, and throughout your ASP.NET programming career. We will also introduce the mindset that will move your applications from being a "brochure" that displays information, into an interactive application delivered over the Web.
Every ASP.NET web site consists of at least one web page stored in a single file with the extension .aspx. There is usually more than one file, as you will see as we go along. The .aspx file is called a content file. Some developers call it the markup file, which makes sense when you remember that HTML stands for HyperText Markup Language.
The contents of the page itself are comprised of "server controls" and "normal" HTML. Server controls are simply controls with code that runs on the server. Normal HTML is sent to the browser "as is." For technical details on how these pages are processed by the web server, see the sidebar below, "How Pages Are Processed on the Server."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Controls
As you've seen in both the examples so far, when you drag a control from the tool-box onto the design surface, it is generally represented as a visible widget to the user. Some controls, however, are used less for display than for manipulating other objects (for example, database manipulation controls) and these are displayed in a special area at the bottom of the main window.
In any case, every control is identified by a unique ID property. Both Visual Web Developer and Visual Studio will automatically assign an ID to your control as you drag it onto your page. These automatically generated IDs are rarely meaningful, and we suggest that you rename them. For example, while the IDE might name your label "Label2," you will probably find it much more useful to rename that label lblPartialUpdate.
When you click on a control in either Design or Source view, its properties are shown in the Properties window. You can change any property value in the Properties window or directly in Source view, and any changes you make will be reflected in both places immediately.
Within the Properties window, you can group properties by category or alphabetically. shows the Accessibility, Appearance, and Behavior categories of a button, though there are others. You can click the appropriate buttons in the menu bar to toggle between the Categorized and Alphabetical views. (When organized alphabetically, the IDof the Control is placed, out of order, at the top of the list, for convenience.)
Figure : The Properties window, as you would expect, shows you the properties of the control you select. You can organize the properties by category, as shown here or alphabetically. You can also view the events associated with the control.
Virtually every control has events associated with it. To view a control's events, click the lightning bolt button. To switch back to properties click the Properties button.

Finding properties with IntelliSense

If you prefer to work in Source view rather than Design view, you can enlist IntelliSense to help you find both the properties and events for any given control. As you press the spacebar, the list of members for the control will be displayed. As you type, IntelliSense will help you fill in the appropriate property or event, as shown in .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Source Code
For your convenience (in case you are away from your computer) the complete source code is shown below. The OrderForm markup is shown in . The code behind file is shown directly after in . Note that although this first example is set up to use AJAX, it does not actually contain any AJAX controls except for the ScriptManager that is added by the IDE; we'll add AJAX starting in the next chapter.
Example . OrderForm.aspx
<%@ Page AutoEventWireup="true" CodeFile="OrderForm.aspx.vb" Inherits="_Default"
   Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
<head runat="server">
   <title>AdventureWorks</title>
</head> 
<body>
   <form id="form1" runat="server">
      <asp:ScriptManager ID="ScriptManager1" runat="server" />
      <div>
         <h1>
            AdventureWorks Order Form
         </h1>
         <table>
            <tr>
               <td >
                  Customer Name:
               </td>
               <td >
                  <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
               </td>
            </tr>
            <tr>
               <td >
                  Address:
               </td>
               <td >
                  <asp:TextBox ID="txtAddress" runat="server" />
               </td>
            </tr>
            <tr>
               <td >
                  City:</td>
               <td >
                  <asp:TextBox ID="txtCity" runat="server"
                  Font-Bold="True" Font-Names="Arial Black" />
               </td>
            </tr>
            <tr>
               <td >
                  State:</td>
               <td >
                  <asp:DropDownList ID="ddlState" runat="server">
                     <asp:ListItem Value="AL">Alabama</asp:ListItem>
                     <asp:ListItem Value="AK">Alaska</asp:ListItem>
                     <asp:ListItem Value="CA">California</asp:ListItem>
                     <asp:ListItem Value="CT">Connecticut</asp:ListItem>
                     <asp:ListItem Value="FL">Florida</asp:ListItem>
                     <asp:ListItem Value="PA">Pennsylvania</asp:ListItem>
                     <asp:ListItem Value="TX">Texas</asp:ListItem>
                     <asp:ListItem></asp:ListItem>
                  </asp:DropDownList></td>
            </tr>
            <tr>
               <td >
                  Zip:</td>
               <td style="width: 100px">
                  <asp:TextBox ID="txtZip" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
               <td >
                  E-mail:
               </td>
               <td >
                  <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
               </td>
            </tr>
            <tr>
               <td >
                  Password:
               </td>
               <td >
                  <asp:TextBox ID="txtPassword" runat="server" 
                       TextMode="Password" />
               </td>
            </tr>
            <tr>
               <td>
                  Comment:</td>
               <td >
                  <asp:TextBox ID="txtComment" runat="server"
                  Rows="3" TextMode="MultiLine" Width="300px" />
               </td>
            </tr>
         </table>
      </div>
      <br />
      Provide personal information:
      <asp:RadioButton ID="rbYes" runat="server" AutoPostBack="True "
          Checked="True" GroupName="grpPersonalInfo"
          Text="Yes"
          ToolTip="Click Yes to gather personal information - no to skip that step" />

      <asp:RadioButton ID="rbNo" runat="server" AutoPostBack="True" 
          GroupName="grpPersonalInfo"
          Text="No"
        ToolTip="Click Yes to gather personal information -no to skip that step " />
      <asp:Panel ID="pnlPersonalInfo" runat="server"
              BorderWidth="1px" Width="300px" BackColor="beige">
         <table>
            <tr valign="top">
               <td>
                  Areas of Interest<br />
                  <asp:CheckBoxList ID="cblAreas"
                     runat="server" AutoPostBack="True" Width="150px">
                     <asp:ListItem>Biking</asp:ListItem>
                     <asp:ListItem>Scuba Diving</asp:ListItem>
                     <asp:ListItem>Gaming</asp:ListItem>
                     <asp:ListItem>Mountain Climbing</asp:ListItem>
                     <asp:ListItem>Web Surfing</asp:ListItem>
                     <asp:ListItem>Real Surfing</asp:ListItem>
                  </asp:CheckBoxList></td>
               <td>
                  Age Category
                  <br />
                  <asp:RadioButtonList ID="rblAge" runat="server"
                  AutoPostBack="True" Width="150px">
                    <asp:ListItem>Under 21</asp:ListItem>
                     <asp:ListItem>Under 21</asp:ListItem>
                     <asp:ListItem>21 to 30</asp:ListItem>
                     <asp:ListItem>31 to 50</asp:ListItem>
                     <asp:ListItem>Over 50</asp:ListItem>

                  </asp:RadioButtonList>
               </td>
            </tr>
         </table>
      </asp:Panel>
      <br />
      <table>
         <tr valign="top">
            <td>
               Product Category:</td>
            <td style="width: 100px">
               <asp:DropDownList ID="ddlCategory" runat="server"
                 ToolTip="Select a category">
                  <asp:ListItem>Bikes</asp:ListItem>
                  <asp:ListItem>Components</asp:ListItem>
                  <asp:ListItem>Clothing</asp:ListItem>
                  <asp:ListItem>Accessories</asp:ListItem>
                  <asp:ListItem>Scuba</asp:ListItem>
                  <asp:ListItem>Parasailing</asp:ListItem>
               </asp:DropDownList></td>
            <td>
               SubCategory:</td>
            <td >
               <asp:ListBox ID="lbSubCategory" runat="server"
               ToolTip="Select a sub-category">
                  <asp:ListItem>Brakes</asp:ListItem>
                  <asp:ListItem>Handlebars</asp:ListItem>
                  <asp:ListItem>Chains</asp:ListItem>
                  <asp:ListItem>Cranks</asp:ListItem>
                  <asp:ListItem>Bottom Brackets</asp:ListItem>
                  <asp:ListItem>Tires</asp:ListItem>
                  <asp:ListItem>Wheels</asp:ListItem>
                  <asp:ListItem>Seats</asp:ListItem>
                  <asp:ListItem>Derailleurs</asp:ListItem>
               </asp:ListBox></td>
         </tr>
      </table>
      <br />
      <asp:CheckBox ID="cbDisplayPhoto"
      runat="server"
      AutoPostBack="True"
      Checked="True"
      Text="Show product photo?"
      TextAlign="Left" />
      <asp:Image ID="imgPhoto"
      runat="server"
      ImageUrl="Dan at Vernal Pool.jpg" />
      <br /><br />

      Summary<br />
      <table>
         <tr>
            <td style="height: 21px" >
               Category:</td>
            <td>
                <asp:Label ID="CategoryLabel" runat="server" Text="" />
            </td>
         </tr>
         <tr>
            <td >
               SubCategory:</td>
            <td>
                <asp:TextBox ID="SubCategoryTextBox" runat="server"
                ReadOnly="true" />
            </td>
         </tr>
         <tr valign="top">
            <td style="height: 21px" >
               Mailing Address:</td>
            <td id="tdAddress" runat="server" style="width:100px; height: 21px;">
            </td>

         </tr>
      </table>
      <br />
      <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
      <br />
      <br />
      For help, contact
      <asp:HyperLink
      ID="hypContact"
      runat="server"
      NavigateUrl="http://www.LibertyAssociates.com"
      Target="_blank">
      Liberty Associates, Inc.
      </asp:HyperLink>
      <br />
   </form>
</body>
</html>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
  • A postback occurs when an event happens on your page that causes the page to return to the server, handle the events, and then send the same page back to the browser. The contents of the page may have changed, but the page object itself is the same.
  • With AJAX, postbacks can be either synchronous, in which case the entire page is returned to the server, or asynchronous, in which case only part of the page is returned to the server.
  • A control is a tool that lets your web page take an action. It could be as simple as displaying some text, or as complicated as interacting with a database. Most controls have some visual representation that the user sees, although not all do.
  • Placing a control in your web page is as simple as dragging it from the Toolbox onto your page; the IDE inserts the appropriate markup for you. Controls all come with at least a few properties and methods, which you can use to customize their appearance and behavior, respectively.
  • Every control has a unique identifier, its ID property. The IDE assigns a default ID automatically, but you can (and usually should) rename them to be more meaningful.
  • Almost every control has associated events, as well as properties. You can access these by clicking the Events button in the Properties window.
  • You can create tables by hand in Source view, or you can use the Insert Table Wizard by selecting Layout → Insert Table in Design view.
  • The TextBox control is a relatively simply control that allows the user to enter text that you can retrieve later. You can change the TextMode property of a TextBox to create single-line entry fields, multiline fields, or to hide the text for a password field.
  • ASP.NET has a number of selection controls, including the ListBox, DropDownList, RadioButton, RadioButtonList, CheckBox, and CheckBoxList, which display various options for the user to choose from. You decide which control to use based on its appearance, and whether you want the user to be able to make only one selection from within a list or multiple selections.
  • If the AutoPostBack property of a control is set to True, the page is posted back to the server whenever that control's value changes.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
BRAIN BUILDER
  1. What is a postback?
  2. What are the two types of postbacks in AJAX, and what is the difference between them?
  3. What property is found on every control?
  4. What control would you use to have the user enter a password, but keep the text hidden?
  5. What control would you use if you have a list of 20 items, and the user can select as many as they want?
  6. How do you make single radio buttons mutually exclusive?
  7. What can you use a Panel control for?
  8. What does the SelectedItem property retrieve?
  9. How do you include a control on the page, but not render it?
  10. What do you do to make the target of a HyperLink control open in a new window?
Exercise 2-1. Now that you've played with HelloWorld, you're going to make a change to the Postbacks example, so you can see how flexible the UpdatePanel control is. Open the Postbacks web site, similar to how you opened HelloWorld in the previous exercise. In Design view, drag another UpdatePanel control inside the first one, after the button. Drag another Label control inside the new UpdatePanel. In the Properties window, set the label's name to lblOtherPartialUpdate, and set its width to 200px. (Note that you can't give this label the same name as the other label—or any other control on the page—or you'll get an error.) Now add another Button to the new UpdatePanel, under the label, set its name to btnOtherPartialUpdate, and change the text to "Another partial-page update:".
Now you need the event handler for your new button, so double-click it, and you'll be taken to the code-behind file. You'll see the event handlers for the two existing buttons already there, and the skeleton for the new event handler. Add the following line of code to this new event handler so it will update with the current time, like the other two buttons do:
	lblOtherPartialUpdate.Text = DateTime.Now
Run your application, and click the buttons. If all went well, you'll see that each label updates independently from the others, and that the two buttons in the update panels don't cause any page flicker. Your page should look something like .
Figure : Your goal for Exercise 2-1. Each label should update independently of the others.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Snappier Web Sites with AJAX
AJAX has revolutionized ASP.NET, and from this moment forward most ASP.NET applications will routinely integrate AJAX controls. AJAX moves ASP.NET applications from being 99% server-side code, to offering the option for a great deal of the processing to happen on the user's browser. The net effect is a tremendous increase in both real and perceived performance of ASP.NET applications.
To demonstrate how much more dynamic and responsive AJAX is, you'll rewrite the order form from , applying Ajax techniques. You'll enhance the site by adding a watermark to user entry fields. A watermark is a bit of text that appears in the text field itself, but disappears as soon as the user starts typing. It serves as an elegant prompt to the user. You will also create a pop-up panel to hide controls until the user needs them, and you'll add a collapsible text field to display product information in a very space-efficient manner.
While server-based web applications have wonderful advantages, they have the obvious disadvantage that any time you want to run any code (or retrieve any data) you must endure the cost of a "round trip" from the browser to the server and back, and the page must be redrawn from scratch. Round trips can be slow (though the Internet is getting faster all the time) and redrawing the page causes a noticeable flicker.
AJAX (which more accurately should be spelled AJX, but that's harder to pronounce) is an acronym for Asynchronous JavaScript and XML—that is, it is a technique for combining well established (some might say old) Internet technology in new ways to greatly enhance the performance of web applications. AJAX enabled applications are very hot—they out-perform server-based applications in ways that would make your jaw drop.
Microsoft, realizing this was not a technology they could ignore, and having learned the lesson that they must leave open standards open, chose to take this very good idea and make it much much better, without making it proprietary.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Take a Walk on the Client Side
While server-based web applications have wonderful advantages, they have the obvious disadvantage that any time you want to run any code (or retrieve any data) you must endure the cost of a "round trip" from the browser to the server and back, and the page must be redrawn from scratch. Round trips can be slow (though the Internet is getting faster all the time) and redrawing the page causes a noticeable flicker.
AJAX (which more accurately should be spelled AJX, but that's harder to pronounce) is an acronym for Asynchronous JavaScript and XML—that is, it is a technique for combining well established (some might say old) Internet technology in new ways to greatly enhance the performance of web applications. AJAX enabled applications are very hot—they out-perform server-based applications in ways that would make your jaw drop.
Microsoft, realizing this was not a technology they could ignore, and having learned the lesson that they must leave open standards open, chose to take this very good idea and make it much much better, without making it proprietary.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
ScriptManager
Microsoft realized that the job of integrating the standard ASP.NET controls and pages with AJAX controls (that encapsulate JavaScript and DHTML) would be difficult, tedious and repetitious. So they did it for you with the ScriptManager control, ensuring that you have access to a fully tested, reliable control that manages the "grunt" work. Adding a ScriptManager control to your page (which the IDE does automatically when you create an AJAX-enabled project) solves the problem, and having one on the page that you don't need comes at virtually no cost. Here is the declaration that must appear in every page, and which is put there for you by the IDE:
	<asp:ScriptManager ID="ScriptManager1" runat="server" />
The ScriptManager control will also be visible in Design view, as shown in , but will not be visible when the web site is run.
Implementing partial-page updates is surprisingly easy using ASP.NET AJAX—you just leave the ScriptManager's EnablePartialRendering property set to its default value of True.
Having done the hard work of not changing that property, you can then drag one or more UpdatePanel controls onto your page. Each UpdatePanel is updated individually and asynchronously, without affecting one another or anything else on the page.
That's it. Instant and unmistakable performance enhancement with almost no programmer effort.
Figure : The ScriptManager control is visible on the page in Design view, but you won't see it in the browser.
To see this dramatic effect, you will modify the AdventureWorks project from the previous chapter, using update panels to improve performance. Recall in that example (shown in ), a pair of radio buttons was created (but never enabled) to control the visibility of a Panel control whose purpose was to collect personal information. You'll enable that feature now.
Normally, clicking on the radio buttons would cause a postback, which would cause the page to flicker as it was redrawn. With an AJAX UpdatePanel, however, the update will be done asynchronously, and there will be no page flicker.
Begin by making a copy of the AdventureWorks Order Form. Call it AdventureWorksRevisited. Run it to ensure that it works as expected.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Extending Controls with the Control Toolkit
The AJAX Control Toolkit provides a number of additional AJAX-enabled controls you can use to enhance the functionality of your web application. Some of the more useful controls in the Control Toolkit are listed in .
Table : A Sample of the AJAX Toolkit Controls
Toolkit Control
Description
Accordion
A control that provides multiple panes, only one of which is visible at a time
AlwaysVisibleControlExtender
Keeps a control visible as the user scrolls the page
AnimationExtender
Helps you animate a panel or other control on your page
CascadingDropDown
The user's selection from one drop down control determines the choices available in the next drop down
CollapsiblePanelExtender
Allows any Panel to collapse and expand
ConfirmButtonExtender
When the user clicks a button, a dialog box pops up to confirm the choice
DragPanelExtender
Lets the user drag a panel around on the page
FilteredTextBoxExtender
Ensures that only "valid" text may be entered into a text box
HoverMenuExtender
Pops up a menu when the mouse hovers over a control
MutuallyExclusive-CheckBoxExtender
Pick none or one of several checkboxes. This provides functionality similar to radio buttons, but with the ability to uncheck all the checkboxes
NoBot
A control which attempts to prevent spam or robot interaction with a web site
NumericUpDownExtender
Adds up/down functionality to a TextBox control; can cycle through numeric values or from a list of provided values
PagingBulletedListExtender
Extends a BulletedList control to provide client-side sorted paging
PasswordStrength
Helps the user pick a good password
Rating
Quick rating, allowing a user to pick the number of stars out of a maximum number (you could use this, for example, to set up a 4-star [or 5-star, or 10-star] rating system for restaurant or movie reviews)
ReorderList
Lets the user reorder the members of a list by dragging them into place
TextBoxWaterMarkExtender
Displays helpful text in a textbox until you start to type
UpdatePanelAnimationExtender
Quick animation of a panel; move, resize, fade
ValidatorCalloutExtender
Extends ASP.NET validation controls by displaying a warning with an image if the field isn't valid
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Source Code Listing
The complete source code for the example in this chapter is shown in .
Example . OrderForm.aspx
<%@ Page Language="VB" AutoEventWireup="true" CodeFile="OrderForm.aspx.vb"
Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <style type="text/css">@import url(StyleSheet.css);</style>
    <title>AdventureWorks CollapsiblePanelExtender</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <div>
        <h1>AdventureWorks Order Form</h1>
            <table>
                <tr>
                    <td style="width: 100px">
                        Customer Name:</td>
                    <td style="width: 100px">
                        <asp:TextBox ID="txtName" runat="server"
                            CssClass="unwatermarked">
                        </asp:TextBox>
                        <cc1:TextBoxWatermarkExtender runat="server"
                            ID="CustomerNameWatermark"
                            TargetControlID="txtName"
                            WatermarkCssClass="watermarked"
                            WatermarkText="Your name">
                        </cc1:TextBoxWatermarkExtender>
                    </td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        Address:</td>
                    <td style="width: 100px">
                        <asp:TextBox ID="txtAddress" runat="server"
                            CssClass="unwatermarked"></asp:TextBox>
                        <cc1:TextBoxWatermarkExtender runat="server"
                                ID="CustomerAddressWatermark"
                                TargetControlID="txtAddress"
                                WatermarkCssClass="watermarked"
                                WatermarkText="Home address">
                        </cc1:TextBoxWatermarkExtender>
                    </td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        City:</td>
                    <td style="width: 100px">
                        <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        State:</td>
                    <td style="width: 100px">
                        <asp:DropDownList ID="ddlState" runat="server">
                            <asp:ListItem Value="AL">Alabama</asp:ListItem>
                            <asp:ListItem Value="AK">Alaska</asp:ListItem>
                            <asp:ListItem Value="CA">California</asp:ListItem>
                            <asp:ListItem Value="CT">Connecticut</asp:ListItem>
                            <asp:ListItem Value="FL">Florida</asp:ListItem>
                            <asp:ListItem Value="PA">Pennsylvania</asp:ListItem>
                            <asp:ListItem Value="TX">Texas</asp:ListItem>
                            <asp:ListItem></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        Zip:</td>
                    <td style="width: 100px">
                        <asp:TextBox ID="txtZip" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        E-mail:</td>
                    <td style="width: 100px">
                        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        Password:</td>
                    <td style="width: 100px">
                        <asp:TextBox ID="txtPassword" runat="server"
                                TextMode="Password"></asp:TextBox></td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        Comment:</td>
                    <td style="width: 100px">
                        <asp:TextBox ID="txtComment" runat="server" Rows="3"
                                TextMode="MultiLine" Width="300px"></asp:TextBox>
                    </td>
                </tr>
            </table>
        </div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
        Provide personal information:
        <asp:RadioButton ID="rbYes" runat="server" AutoPostBack="True"
            Checked="True"
            GroupName="grpPersonalInfo"
            Text="Yes" ToolTip="Do gather personal info" />
        <asp:RadioButton ID="rbNo" runat="server" AutoPostBack="True"
            GroupName="grpPersonalInfo"
            Text="No" ToolTip="Do not gather personal info" /><br />
        <asp:Panel ID="pnlPersonalInfo" runat="server" BorderWidth="1px">
            <table>
                <tr valign="top">
                    <td >
                        Areas of Interest<br />
                        <asp:CheckBoxList ID="cblAreas" runat="server"
                                AutoPostBack="True" Width="150px">
                            <asp:ListItem>Biking</asp:ListItem>
                            <asp:ListItem>Scuba Diving</asp:ListItem>
                            <asp:ListItem>Gaming</asp:ListItem>
                            <asp:ListItem>Mountain Climbing</asp:ListItem>
                            <asp:ListItem>Web Surfing</asp:ListItem>
                            <asp:ListItem>Real Surfing</asp:ListItem>
                        </asp:CheckBoxList></td>
                    <td style="width: 121px">
                        Age Category<br />
                        <asp:TextBox ID="txtAgeCategory" runat="server"
                            Width="175px">
                        </asp:TextBox><br />

                        <cc1:TextBoxWatermarkExtender
                            ID="TextBoxWatermarkExtender1" runat="server"
                            TargetControlID="txtAgeCategory"
                            WatermarkText="Click here for age categories">
                        </cc1:TextBoxWatermarkExtender>
                        <cc1:PopupControlExtender ID="PopupControlExtender1"
                            runat="server"
                            TargetControlID="txtAgeCategory"
                            PopupControlID="pnlAgeCategories"
                            Position="Bottom">
                        </cc1:PopupControlExtender>
                        <asp:Panel ID="pnlAgeCategories" runat="server"
                            Height="50px" Width="125px">
                            <asp:UpdatePanel ID="UpdatePanel2" runat="server">
                                <ContentTemplate>
                        <asp:RadioButtonList ID="rblAge" runat="server"
                                AutoPostBack="True" Width="150px"
                              OnSelectedIndexChanged="rblAge_SelectedIndexChanged">
                            <asp:ListItem Value="Under 21 - Enjoy it!">Under 21
                                    </asp:ListItem>
                            <asp:ListItem Value="21 to 30 - Livin' Large">21 to 30
                                    </asp:ListItem>
                            <asp:ListItem Value="31 to 50 - Life Is Good">31 to 50
                                    </asp:ListItem>
                            <asp:ListItem Value="Over 50 - Golden Years">Over 50
                                    </asp:ListItem>
                        </asp:RadioButtonList>
                                </ContentTemplate>
                            </asp:UpdatePanel>
                        </asp:Panel>
                    </td>
                </tr>
            </table>
        </asp:Panel>
            </ContentTemplate>
        </asp:UpdatePanel>
        <br />
        <asp:Panel ID="pnlProductInfoHeader" runat="server"
                        Height="50px" Width="125px">
            <asp:Image ID="imgProductInfo_ToggleImage" runat="server"
                ImageUrl="collapse.jpg" /><br />
            Product Information</asp:Panel>
        <asp:Panel ID="pnlProductInfo" runat="server" BackColor="LightGray"
            Width="450px">
            <asp:Label ID="myLabel" runat="server" Text=
            "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
   Aliquam eleifend, turpis sit amet tincidunt euismod, urna eros mattis
   neque, vitae facilisis nulla dui ut dolor. Proin pretium. Etiam ultrices
   eleifend neque. Mauris vestibulum purus quis nibh. Phasellus dignissim.
   Vivamus laoreet magna id purus. In hac habitasse platea dictumst. Vivamus
   congue elit quis arcu. Sed lorem mauris, convallis non, porta sed, interdum
   id, nisl. Aenean id tortor. Sed ac quam. Suspendisse ornare luctus sapien.
   Praesent aliquet, lacus nec venenatis placerat, massa metus mattis dolor,
   non eleifend pede sapien et lorem. Curabitur dapibus faucibus nunc.">
            </asp:Label>
            <br />
            <br />
            <asp:Image ID="Image1" runat="server"
                        ImageUrl="Dan at Vernal Pool.jpg" />
        </asp:Panel>
        <cc1:CollapsiblePanelExtender ID="cpeProductInfo" runat="server"
            CollapseControlID="pnlProductInfoHeader"
            Collapsed="true"
            CollapsedImage="expand.jpg"
            CollapsedText="Product Information (Show Details...)"
            ExpandControlID="pnlProductInfoHeader"
            ExpandedImage="collapse.jpg"
            ExpandedText="Product Information (Hide Details...)"
            ImageControlID="imgProductInfo_ToggleImage"
            SuppressPostBack="true"
            TargetControlID="pnlProductInfo">
        </cc1:CollapsiblePanelExtender>

    </form>
</body>
</html>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
  • AJAX is a technique for processing code on the server, and on the user's browser, which dramatically increases performance, both actual and perceived.
  • The ASP.NET AJAX control library contain a number of controls that can be used just as easily as standard ASP.NET controls, meaning you don't need to know the JavaScript behind how the controls work.
  • The ScriptManager control is the key control that makes ASP.NET AJAX possible by managing the JavaScript for you. The control is placed on everyAJAX-enabled page by default, and its EnablePartialRendering property is set to True, so you don't need to do anything yourself.
  • Placing controls inside an UpdatePanel control enables you to update those controls without posting back to the server.
  • The AJAX Control Toolkit, which is a separate download, has a number of controls called extenders that enhance existing controls, rather than being separate controls themselves. Extender controls have a TargetControlID property that you use to set the existing control that the extender is extending.
  • The TextBoxWaterMarkExtender adds a watermark effect to an existing textbox, providing a prompt for the reader to enter data.
  • TextBoxWaterMarkExtender can apply a separate style to a text box, if you have a style sheet defined for the project, or it can just add the text you specify.
  • The PopupControlExtender can help you make efficient use of the space on your page, by hiding some content until the user clicks on a control.
  • You can apply the CollapsiblePanelExtender to a regular Panel control, causing it to hide most of its content until the user clicks on it. The Panel then expands, displaying its content, until the user collapses it.
Now you have a good handle on the basic controls, and you've also seen how to use some of the AJAX extenders to apply