Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ASP.NET 2.0 Everyday Apps For Dummies (2006)

.pdf
Скачиваний:
56
Добавлен:
17.08.2013
Размер:
10.07 Mб
Скачать

Chapter 6: Building a Shopping Cart Application 187

<br />

 

<asp:Label ID=”Label12” runat=”server”

 

BorderStyle=”None” Text=”Shipping:”

 

Width=”80px” />

 

<asp:Label ID=”lblShipping”

20

runat=”server” />

 

<br />

 

<asp:Label ID=”Label14” runat=”server”

 

BorderStyle=”None” Text=”Total:”

 

Width=”80px” />

 

<asp:Label ID=”lblTotal”

21

runat=”server” />

 

<br /><br />

Click Submit Order to complete your order.<br /> </asp:WizardStep>

</WizardSteps>

<SideBarStyle VerticalAlign=”Top” /> 22 </asp:Wizard>

</asp:Content>

This is a long listing because the Wizard control has three steps, each of which is like an entire Web page unto itself. The following list describes each of the controls defined for this page:

1 In the Page directive, remember to change the Language attribute to VB and the AutoEventWireup attribute to false if you’re working with Visual Basic.

2 The Wizard control defines the wizard displayed by the Check Out page. The ActiveStepIndex attribute specifies the index of the step the wizard should start with when the page is first displayed, and the FinishCompleteButtonText attribute specifies the text displayed on the Finish button in the final step of the wizard.

Whenever you run the application from Visual Studio, this attribute is changed to match the step that is currently displayed in the design window. As a result, you should always switch to the first Wizard step before running the application from Visual Studio.

If you’re working in Visual Basic instead of C#, you should remove the OnFinishButtonClick attribute.

3 The <WizardSteps> element defines the steps used by the wizard. Each of these steps is then defined by an <asp:WizardStep> element. This one defines the first step in the Wizard, titled “Shipping.” The content for this step begins with the text “Where do you want this order shipped?” Then items 4 through 11 define the controls that allow the user to enter the shipping information.

4 A label, text box, and required-field validator let the user enter his or her last name.

188 Part III: Building E-Commerce Applications

5 A label, text box, and required-field validator let the user enter his or her first name.

6 A label, text box, and required-field validator let the user enter his or her address.

7 A label, text box, and required-field validator let the user enter the city.

8 A label and a drop-down list let the user select the state. As you can see, 51 <ListItem> elements are used to populate the dropdown list with the names and abbreviations of the 50 states plus the District of Columbia.

9 A label, text box, and required-field validator let the user enter his or her Zip code.

10 A label, text box, and required-field validator let the user enter his or her phone number.

11 A label, text box, and required-field validator let the user enter his or her e-mail address. This is the last set of controls for the first wizard step.

12 The second wizard step defines the controls that let the user enter his or her credit card information. This step is titled “Billing.”

13 A label and a drop-down list let the user choose the credit card type. <ListItem> elements are used to fill the drop-down list with three popular credit card types: Visa, MasterCard, and American Express. If you want to accept additional credit card types, you can add additional <ListItem> elements.

14 A label, text box, and required-field validator let the user enter the credit card number. For an actual application, you’ll want to do more validation than a simple required-field validator provides. In particular, you’ll want to make sure that the number entered conforms to the requirements for each credit card type. (The requirements vary depending on card type; I’ll leave it to you to provide this validation.)

15 A label and drop-down list let the user select the credit card’s expiration month. Twelve <ListItem> elements fill the list with the months of the year.

16 A label, text box, and two validators let the user enter the year the credit card expires. The required-field validator ensures that the user enters a value, and the range validator requires that the entry be an integer between 2005 and 2099.

Note that this validation logic doesn’t prevent the user from entering data based on a card that’s already expired. You may want to provide more extensive validation here to ensure that the year is greater than or equal to the current year — and (if the year is equal to the current year) that the month is greater than or equal to the current month.

Chapter 6: Building a Shopping Cart Application 189

17 The third wizard step defines the final step of the check-out process, which simply displays a summary of the order and allows the user to submit the order for final processing. The title of this step is “Confirmation.”

18 This label displays the order subtotal, obtained by adding the total for each item in the shopping cart.

19 This label displays the sales tax for the order.

20 This label displays the shipping charges for the order.

21 This label displays the order total. This is the last control in the third wizard step.

22 The Wizard control ends with a <SideBarStyle> element that defines how the sidebar navigation links will be aligned. In this case, VerticalAlign=”Top” indicates that the links will appear at the top of the sidebar area. By default, they are centered vertically.

The code-behind file for the Check Out page

Mercifully, the code-behind file for the Check Out page is not nearly as long as the .aspx file (or as long as the code-behind for the Cart page, for that matter). Listing 6-11 shows the C# version, and the Visual Basic version is shown in Listing 6-12.

Listing 6-11: The code-behind file for the Check Out page (C#)

using System; using System.Data;

using System.Configuration; using System.Collections; using System.Web;

using System.Web.Security; using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;

public partial class CheckOut : System.Web.UI.Page

 

{

 

private Order order;

1

private Customer cust;

 

private ShoppingCart cart;

 

protected void Page_Load(object sender,

2

EventArgs e)

 

{

 

(continued)

190 Part III: Building E-Commerce Applications

Listing 6-11 (continued)

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

 

if (Session[“order”] == null)

3

{

 

order = new Order(DateTime.Now,

 

null, (ShoppingCart)Session[“cart”]);

 

Session[“order”] = order;

 

}

 

else

 

{

 

order = (Order)Session[“order”];

 

cart = order.Cart;

 

}

 

cust = new Customer(txtLastName.Text,

4

txtFirstName.Text,

 

txtAddress.Text,

 

txtCity.Text,

 

ddlState.SelectedValue,

 

txtZipCode.Text,

 

txtPhoneNumber.Text,

 

txtEmail.Text);

 

order.Cust = cust;

 

lblSubtotal.Text

5

= order.SubTotal.ToString(“c”);

 

lblSalesTax.Text

 

= order.SalesTax.ToString(“c”);

 

lblShipping.Text

 

= order.Shipping.ToString(“c”);

 

lblTotal.Text

 

= order.Total.ToString(“c”);

 

}

 

protected void Wizard1_FinishButtonClick(

6

object sender, WizardNavigationEventArgs e)

 

{

 

// process credit card information here

 

bool success = OrderDB.WriteOrder(order); Session[“cart”] = null;

Session[“order”] = null; if (success)

Response.Redirect(“Completed.aspx”); else

Response.Redirect(“Completed.aspx?Error=1”);

}

}

Chapter 6: Building a Shopping Cart Application 191

The Wizard Control

The Wizard control is a new feature in ASP.NET 2.0 that makes it easy to create wizards that walk the user through a series of steps. A wizard consists of one or more steps and navigation buttons that let the user move from step to step. Only the content defined for the current step is displayed when the page containing a Wizard control is rendered.

The steps for the Wizard control are defined by the <WizardSteps> element, which can contain one or more <WizardStep> child elements. There are five different types of steps you can create:

Start: The first step. This step includes a Next button but not a Previous button.

Step: An intermediate step. This step includes both a Next and a Previous button.

Finish: The final step that collects data from the user. Instead of a Next button, this step includes a Finish button.

Complete: The last step displayed by the wizard, after the user clicks the Finish button. No navigation buttons are included on this step.

Auto: A step whose type is determined by its position in the <WizardSteps> element. (For example, the first step declared is the start step.)

Here’s a basic skeleton of a simple Wizard control with three steps:

<asp:Wizard id=”Wizard1” runat=”server”> <WizardSteps>

<asp:WizardStep steptype=”Start” title=”Step One”> Content for step one goes here.

</asp:WizardStep>

<asp:WizardStep steptype=”Step” title=”Step Two”> Content for step two goes here.

</asp:WizardStep>

<asp:WizardStep steptype=”Finish” title=”Step

Three”>

Content for step three goes here. </asp:WizardStep>

</WizardSteps>

</asp:Wizard>

Note that you can edit the steps individually in Visual Studio using the Smart Tag menu, which you can summon by clicking the small arrow that appears in the upper-right corner of the Wizard when you’re working in Design view.

You can select the step you want to edit from a drop-down list that appears in the Smart Tag menu. And you can add or remove steps by choosing Add/Remove WizardSteps from the Smart Tag menu.

192 Part III: Building E-Commerce Applications

The following paragraphs explain the key points of this code-behind file:

1 Three variables are defined so they can be accessed throughout the class. The first, order, references the Order object for the order to be processed. The second, cust, references the Customer object.

And the third, cart, references the user’s shopping cart.

2 The Page_Load method is executed each time the page loads. It begins by retrieving the shopping cart from session state and assigning it to the cart variable.

3 This if statement retrieves the order item from session state if it exists. If there is no order item already in session state, a new Order object is created using the current time for the order date, null (C#) or Nothing (VB) for the customer, and the cart item from session state for the shopping cart. Then the new Order object is added to session state.

4 Next, a new Customer object is created, using values entered by the user in the first wizard step. Note that if the user hasn’t yet completed this step, these values will be blank. The new Customer object is then assigned to the Cust property of the order object.

5 These four assignment statements assign formatted values to the labels in the Confirmation step of the wizard, using properties of the Order object.

6 The Wizard1_FinishButtonClick method is called when the user clicks the Submit Order button in the third wizard step. It begins with a comment that indicates where you should place the code that processes the customer’s credit card. Then it calls the WriteOrder method of the OrderDB class to write the order to the database. The result of this call is saved in the Boolean variable success. Next, the cart and order items in session state are cleared. Finally, the user is redirected to the Completed.aspx page. A query string field named Error is passed if the WriteOrder method returned false.

Listing 6-12: The code-behind file for the Check Out page (VB)

Partial Class CheckOut

Inherits System.Web.UI.Page

Private order

As Order

1

Private cust As Customer

 

Private cart As ShoppingCart

 

Protected Sub Page_Load( _

2

ByVal sender As Object, _

 

ByVal e As System.EventArgs) _

 

Handles Me.Load

 

Chapter 6: Building a Shopping Cart Application 193

cart = Session(“cart”)

 

If Session(“order”) Is Nothing Then

3

order = New Order(DateTime.Now, _

 

Nothing, Session(“cart”))

 

Session(“order”) = order

 

Else

 

order = Session(“order”)

 

cart = order.Cart

 

End If

 

cust = New Customer(txtLastName.Text, _

4

txtFirstName.Text, _

 

txtAddress.Text, _

 

txtCity.Text, _

 

ddlState.SelectedValue, _

 

txtZipCode.Text, _

 

txtPhoneNumber.Text, _

 

txtEmail.Text)

 

order.Cust = cust

 

lblSubtotal.Text _

5

= order.SubTotal.ToString(“c”)

 

lblSalesTax.Text _

 

= order.SalesTax.ToString(“c”)

 

lblShipping.Text _

 

= order.Shipping.ToString(“c”)

 

lblTotal.Text _

 

= order.Total.ToString(“c”)

 

End Sub

 

Protected Sub Wizard1_FinishButtonClick( _

6

ByVal sender As Object, _

 

ByVal e As

 

System.Web.UI.WebControls.WizardNavigationEvent

Args) _

 

Handles Wizard1.FinishButtonClick

 

‘ process credit card information here

 

Dim success As Boolean

success = OrderDB.WriteOrder(order) Session(“cart”) = Nothing Session(“order”) = Nothing

If success Then Response.Redirect(“Completed.aspx”)

Else Response.Redirect(“Completed.aspx?Error=1”)

End If End Sub

End Class

194 Part III: Building E-Commerce Applications

Creating the Customer Class

The Customer class provides the customer information required to process an order. Its constructors and properties are spelled out earlier in this chapter (refer to Table 6-4). Listing 6-13 shows the C# version of this class. The Visual Basic version is shown in Listing 6-14.

Listing 6-13: The Customer class (C# version)

using System; using System.Data;

using System.Configuration; using System.Web;

using System.Web.Security; using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;

public class Customer

{

private string _lastName; private string _firstName; private string _address; private string _city; private string _state; private string _zipCode; private string _phoneNumber; private string _email;

public Customer()

{

}

public Customer(string lastName, string firstName, string address, string city, string state,

string zipCode, string phoneNumber, string email)

{

this.LastName = lastName; this.FirstName = firstName; this.Address = address; this.City = city; this.State = state; this.ZipCode = zipCode;

this.PhoneNumber = phoneNumber; this.Email = email;

}

public string LastName

1

2

3

4

Chapter 6: Building a Shopping Cart Application 195

{

get

{

return _lastName;

}

set

{

_lastName = value;

}

}

public string FirstName

{

get

{

return _firstName;

}

set

{

_firstName = value;

}

}

public string Address

{

get

{

return _address;

}

set

{

_address = value;

}

}

public string City

{

get

{

return _city;

}

set

{

_city= value;

}

}

public string State

{

get

{

5

6

7

8

(continued)

196 Part III: Building E-Commerce Applications

Listing 6-13 (continued)

return _state;

}

set

{

_state = value;

}

}

public string ZipCode

{

get

{

return _zipCode;

}

set

{

_zipCode = value;

}

}

public string Email

{

get

{

return _email;

}

set

{

_email = value;

}

}

public string PhoneNumber

{

get

{

return _phoneNumber;

}

set

{

_phoneNumber = value;

}

}

}

9

10

11

The following paragraphs define each component of this class:

1 The class begins by defining private instance variables that are used to hold the values associated with the class properties. By convention, each of these variable names begins with an