• No results found

Creating Multipage Applications

Book VIII: Advanced ASP.NET Programming

Chapter 5: Creating Multipage Applications

In This Chapter

Learning the basics of a multipage application

Adding pages to a Web project

Getting from one page to another

Keeping track of an application’s state

Dipping your toe into data binding

Using Master Pages to create a consistent look among your pages

O

nly the most trivial and boring of Web sites have just one page. Most Web sites go way beyond one page — perhaps to dozens or even hun- dreds of pages. Pervasive as they are, these multipageWeb sites present sev- eral interesting challenges. This chapter shows how to add pages to your Web applications — and deal with the complications that result from having multiple pages. Those include such issues as how your users can get from one page to another, how to create pages that have a consistent appear- ance, and how to manage the “state” of an application so the application knows where it’s been and where it’s going.

All code listings used in this book are available for download at www. dummies.com/go/aspnetaiofd.

Understanding the Basics of a Multipage Application

To illustrate the programming techniques you’ll learn in this chapter, we’ll take a close look at a simple shopping cart application, similar to many simi- lar applications you’ve undoubtedly encountered on the Web. Of course, this application is dramatically simplified so we can focus on a few basic programming techniques. For example, this online store (which sells Halloween costumes) has only a few products for sale. And the shopping cart doesn’t mention the price of the products you buy — just the descrip- tion and quantity of each product. (Hey, why not? Imaginary stores can afford to be simplistic.)

Understanding the Basics of a Multipage Application

64

Figure 5-1 shows the first page of the Shopping Cart application, Default. aspx. Here you can see that the page consists of three controls: a list box from which you can select a product, a text box in which you can enter a quantity, and a button you can click to add the selected product to your shopping cart.

When the user selects a product, enters a quantity, and clicks the button, the application adds the selected product to the user’s shopping cart. Then the application displays the second page of the application — Cart.aspx— as shown in Figure 5-2, where a list box displays the contents of the user’s shopping cart. Figure 5-2: The second page of the Shopping Cart application. Figure 5-1: The first page of the Shopping Cart application.

Book I Chapter 5

Creating Multipage

Applications

Understanding the Basics of a Multipage Application

65

The second page of the Shopping Cart application has two buttons. The first simply returns to the first page so the user can change what’s in the shop- ping cart by adding or removing items. The second button is a Check Out button that . . . okay . . . doesn’t do anything in this particular application. It’s there only because in a realistic Shopping Cart application, you’d see a button that lets the user complete the order.

Although this application is simple, it utilizes some important ASP.NET pro- gramming techniques — in particular, these:

The application uses two pages, so it must provide a way for one page to lead to the other.For example, when the user clicks the Add To Cart button on the Default.aspxpage, the application displays the Cart. aspxpage. And when the user clicks the Continue Shopping button on the Cart.aspxpage, the application displays the Default.aspxpage. (For more about adding pages to your Web site and navigating between them, see the “Adding Pages” section later in this chapter.)

In addition to the classes that represent theDefault.aspxand Cart.aspxpages, the application uses a custom class called ShoppingCartItemto represent the items in the shopping cart.

(Books 3 and 4 get into the fine details of classes).

The application uses an ASP.NET programming feature called session

state to store the actual shopping cart data.A .NET Framework class called ArrayList— which is designed to store collections of repeating data — stores the data and keeps track of the session state. (For more about how that works, see the “Using Session State” section later in this chapter.)

The application uses another ASP.NET programming feature called

data binding for automatic display of the data stored in the shopping

cart’s ArrayListobject.The data shows up on-screen in the list box that appears in the Cart.aspxpage. (This chapter gives you a glimpse of data binding, but the best in-depth look is in Book 6.)

Notice how both pages in this application have the same graphic displayed at the top?You could simply copy and paste this graphic on each page. But there’s a better way: Master Pages. The Master Page fea- ture makes it easy to create applications whose pages have common ele- ments such as banners, navigation menus, and so on. (For the masterful details, see the “Using Master Pages” section later in this chapter.) The rest of this chapter takes a closer look at each of these programming techniques. Then I present the code for the Shopping Cart application so you can see how everything works together.

Adding Pages

66

Adding Pages

When you first create an ASP.NET Web application, the application consists of a single Web page named Default.aspx. Few applications use just a single page, so one of the first things you have to get Visual Studio to do is add a new page to your Web site. Fortunately, the procedure is relatively simple. Just follow these steps:

1.

Choose WebsiteAdd New Item.

If you prefer, you can use one of the following shortcuts: • Ctrl+Shift+A.

The Add New Item button in the Standard toolbar (shown in the margin).

Right-click the project in the Solution Explorer, then choose Add New Item.

Either way, the Add New Item dialog box appears, as shown in Figure 5-3.

2.

Make sure Web Form is selected in the Templates box.

Usually this item is already selected. But check to make sure.

3.

Enter a name for the page in the Name text box.

The default name is — ahemDefaultx.aspx. Now, I’m guessing you don’t want to create a Web site full of pages named Default1.aspx,

Default2.aspx, and so on. So give your page a more meaningful name.

4.

Select the programming language.

Figure 5-3:

The Add New Item dialog box.

Book I Chapter 5

Creating Multipage

Applications

Redirecting to Another Page

67

The default is the language you chose when you created the Web site. Sure, you canmix languages within a single Web site, but it’s seldom a good idea to do so. Normally it’s best to leave this option untouched.

5.

Make sure the Place Code in Separate File option is checked.

This option, which is checked by default, creates a code-behind file for the page’s event handlers. If you don’t want to use a code-behind file, uncheck this option.

6.

If you’re using Master Pages, check the Select Master Page option.

For more about how Master Pages work, see the “Using Master Pages” section later in this chapter.

7.

Click Add.

Visual Studio grinds and whirs for a moment, and then adds the page. You’ll see an icon for the new page in the Solution Explorer, and the

.aspxfile opens in the Web Designer window. (If you selected C# as your language, the page opens in Source view; if you selected Visual Basic, the page opens in Design view.)

You can, of course, add as many pages as you want to an ASP.NET project. If a project requires a lot of pages, you may want to use subfolders to organize the pages. To create a subfolder, right-click the project in the Solution Explorer and choose New Folder. Then type a name for the new folder and press Enter.

Redirecting to Another Page

When your Web site has more than one page in it, you need a way to take the user from one page to another. ASP.NET provides several ways to do this. The most common is to call Response.Redirectin the Clickevent handler for a button. For example, if you want the page Default.aspxto be displayed when the user clicks a button named btnContinue, you would code the following C# event handler for the btnContinuebutton:

protected void btnContinue_Click(object sender, EventArgs e)

{

Response.Redirect(“Default.aspx”); }

The VB.NET version of this event handler would look like this:

Protected Sub btnContinue_Click( _ ByVal sender As Object, _

Adding Classes

68

ByVal e As System.EventArgs) _ Handles btnContinue.Click Response.Redirect(“Default.aspx”) End Sub

An alternative to the Response.Redirectmethod is another method,

Server.Transfer. The difference between Response.Redirectand

Server.Transferis pretty straightforward:

✦ Response.Redirectactually sends a message to the user’s browser, instructing it to post a request for a different page back to the user.

As a result, this technique requires an additional round-trip between the server and the browser.

In contrast, theServer.Transfermethod simply transfers the server directly to the other page, so an additional round-trip isn’t needed.

You might think that Server.Transferwould be preferred because it avoids the extra round-trip over the Internet, but it turns out that Server. Transferhas a serious limitation: The user’s browser continues to display the original page in its Address bar. So if you want to display a page other than the one posted by the user, and you want the user to see the address of the new page, you should use Response.Redirectinstead.

A new technique that’s available in ASP.NET 2.0 is called cross-page posting:

You create a button control that automatically posts back to a different page. To use cross-page posting, you use the PostBackURLattribute to specify the page you want to post to. For example, here’s the markup that creates a button that posts to a page named Default.aspx:

<asp:Button ID=”btnContinue” runat=”server” Text=”Continue Shopping”

PostBackURL=”~/Default.aspx” />

Whenever you find yourself coding a Clickevent handler for a button, and it consists of nothing other than a call to Response.Redirect, consider using cross-page posting instead.

Adding Classes

In addition to other Web pages, you can also add classes to an ASP.NET applica- tion. The Shopping Cart application uses a class to represent each item in the shopping cart. This class, called ShoppingCartItem, defines three properties:

Book I Chapter 5

Creating Multipage

Applications

Adding Classes

69

Description, Quantity, and ItemLine. The Descriptionproperty provides a text description of the item, while the Quantityproperty provides the quan- tity of the item requested by the user. The ItemLineproperty provides a simple text string that’s displayed in the shopping cart.

To add a class to a Web site, follow these steps:

1.

Choose WebsiteAdd New Item.

If you prefer, you can use one of the following shortcuts: • Ctrl+Shift+A.

The Add New Item button in the Standard toolbar (shown in the margin).

Right-click the project in the Solution Explorer, then choose Add New Item.

One way or another, the Add New Item dialog box that was shown back in Figure 5-3 appears.

2.

Select Class in the Templates box.

Usually this item is already selected. But check to make sure.

3.

Enter a name for the class in the Name text box.

The default name is Class1. You can do better than that.

4.

Select the programming language.

Once again, this defaults to the language you selected for the project. You’d best not change it.

5.

Click Add.

The class file is added to the App_Codefolder, a special folder desig- nated for holding your class files.

If this is the first class you are adding to a project, Visual Studio will dis- play a dialog box asking if you want to create the App_Codefolder. Click Yes to create the folder.

After the class has been created, it’s displayed in the Code Editor, as shown in Figure 5-4.

6.

Edit the class any way you like.

For the Shopping Cart application, you’ll want to add code that implements the shopping cart functionality the application needs, as described in the following paragraphs.

Adding Classes

70

As you can see in Figure 5-4, the class file created when you add a class to a project contains some skeleton programming elements — such as using

statements (known as Importsin VB.NET), comments, a class declaration, and an empty constructor.

Here is the complete C# code for the ShoppingCartItemclass after I fin- ished editing it:

public class ShoppingCartItem {

public string Description; public int Quantity;

public ShoppingCartItem(string description, int quantity)

{

Description = description; Quantity = quantity; }

public string ItemLine {

get {

string line = Quantity.ToString() + “ “ + Description; if (Quantity == 1) line += “ costume”; else line += “ costumes”; Figure 5-4: A new class file, ready for you to program.

Book I Chapter 5

Creating Multipage

Applications

Using Session State

71

return line; }

} }

As you can see, I removed the using statements that aren’t required for this class, added two public fields (Descriptionand Quantity), a constructor, and a property named ItemLine.

The VB.NET version of this class looks like this:

Public Class ShoppingCartItem Public Description As String Public Quantity As Integer

Public Sub New(Description As String, _ Quantity As Integer)

Me.Description = Description Me.Quantity = Quantity End Sub

Public ReadOnly Property ItemLine As String Get

Dim Line As String

Line = Quantity.ToString() & “ “ _ & Description

If Quantity = 1 Then

Line = Line & “ costume” Else

Line = Line & “ costumes” End If

Return line End Get

End Property End Class

If you find yourself staring confusedly at “The C# Version of the Shopping Cart Application” (later in this chapter) and the code shown in Listings 5-1 or 5-2 seems no less dense, you may want to skip ahead to Book 4 or Book 5 for a refresher on the basics of C# or VB.NET programming. They should clear up that headache right away.

Using Session State

One of the most important things to know about ASP.NET application program- ming is that whenever a page is sent to the user’s browser, the program that created the page no longer exists in the server’s memory. As a result, the typi- cal ASP.NET program has a very short actual lifetime — which goes like this:

Using Session State

72

1.

The user clicks a button or takes some other action that causes a page to be posted to the server.

2.

The server determines which page was posted by the user, locates the program that corresponds to that page, and starts the program.

3.

The program retrieves any data entered by the user, generates HTML

for the page, and sends it back to the user.

4.

The generated page is sent back to the user’s browser.

5.

The program ends.

When a user works with an ASP.NET application, he or she repeats this sequence of steps many times. Collectively, this is referred to as the user’s

session.

A critical aspect of any ASP.NET application is keeping track of the applica- tion’s status during each user’s session. For example, the Shopping Cart application must keep track of what’s in the user’s shopping cart. The shop- ping cart can’t simply be stored as a program variable because the program ends when a page is sent back to the user. As a result, the program must find some other way to store the contents of the shopping cart.

There are several ways to store this kind of information during a user’s ses- sion. One of the most common ways is the ASP.NET session state feature: ASP.NET creates and maintains an object called the Session objectfor each user who accesses an application. The application can use this object to store and retrieve data between pages.

The Sessionobject can be accessed as a property of the Pageclass, from which all ASP.NET pages are derived. The Sessionobject maintains a collec- tion of data items. Each item has both a name and a value. The value can be any type of object, from a simple string or number to a complex object cre- ated from a .NET Framework class. For example, the Shopping Cart applica- tion uses an object created from the .NET ArrayListclass to store the user’s shopping cart.

Here’s a C# example of code that creates an ArrayListobject and adds it to session state using the name cart:

ArrayList cart = new ArrayList(); Session[“cart”] = cart;

Book I Chapter 5

Creating Multipage

Applications

Using Session State

73

Dim cart As New ArrayList() Session(“cart”) = cart

Here’s an example (in C#) of how to retrieve an item from session state:

ArrayList cart = (ArrayList)Session[“cart”];

Note that you must cast the item to an ArrayListtype. And here’s the VB.NET version:

Dim cart As ArrayList = CType(Session(“cart”), ArrayList)

In many applications, you need to test whether an item exists in session state. If so, you simply retrieve the item. If not, you create a new item and add it. Here’s C# code that does just that:

ArrayList cart;

if (Session[“cart”] == null) {

cart = new ArrayList(); Session[“cart”] = cart; } else { cart = (ArrayList)Session[“cart”]; }

Here’s VB.NET code that does the same thing:

Dim cart As ArrayList

If Session(“cart”) Is Nothing Then cart = New ArrayList()

Session(“cart”) = cart Else

cart = CType(Session(“cart”), ArrayList) End If

Here are a few additional details you need to know about session state:

ASP.NET automatically keeps track of user sessions.When a user hasn’t posted a page after a certain amount of time (typically 20 min- utes), the session is closed and any objects stored in session state are deleted.

A single user can have two sessions open at the same time.This can happen if the user visits your application using two separate browser

Looking into Data Binding

74

windows. Don’t worry, ASP.NET is able to keep these browser sessions