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

Beginning ASP.NET 2

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

E-Commerce

NewItem.ProductImageUrl = ProductImageUrl _items.Add(NewItem)

Else

_items(ItemIndex).Quantity += 1 End If

_lastUpdate = DateTime.Now() End Sub

When you add a new item into the cart (the Insert method), you need to create an index to track this. If the index is –1, you know that item is not already present in the cart, and you need to create a new cart item with the accompanying ProductID, Quantity, Price, ProductName, and ProductImageUrl details. If it is present, you just need to add one to the quantity. Because you have just made the last update to the cart, you also need to record this in the lastUpdate variable and use the DateTime.Now() function to record the current date and time.

The Update action is in fact just a recalculation of Price; as mentioned earlier, Quantity is the only item you can actually change when you update the cart details. (If you think about it this makes total sense, because you can’t have the customers updating the price, or the product name or description anyway.) The quantity affects the price.

Public Sub Update(ByVal RowID As Integer, ByVal ProductID As Integer, _

ByVal Quantity As Integer, ByVal Price As Double)

Dim Item As CartItem = _items(RowID)

Item.ProductID = ProductID

Item.Quantity = Quantity

Item.Price = Price

_lastUpdate = DateTime.Now()

End Sub

You identify the item once again using the index, and you read the ProductID, the Quantity, and the Price from the CartItem collection, and set it to the new Quantity for your chosen product. You update the time the cart was updated as well.

You’ve looked at the Update and Insert methods, so that just leaves the question of how customers can remove items from the cart. This is done via the Delete method. The Delete method is the simplest of the three; all you need to do is use the index to identify which item has been selected for deletion and remove it with the RemoveAt method. You also set the _lastUpdate variable to contain the current time, because you have just updated the cart by deleting an item from it:

Public Sub DeleteItem(ByVal rowID As Integer) _items.RemoveAt(rowID)

_lastUpdate = DateTime.Now() End Sub

Under the Insert, Update, and DeleteItem methods is the index property. The index property is as follows:

Private Function ItemIndexOfID(ByVal ProductID As Integer) As Integer Dim index As Integer

For Each item As CartItem In _items If item.ProductID = ProductID Then

Return index

489

Chapter 13

End If index += 1

Next Return -1

End Function

The index, which is used to identify each item in the cart, stores each product’s Product ID. If the first item in the cart was a scarf, then the first item in the index will contain the scarf’s ProductID. If you haven’t got a ProductID, you return -1 instead to indicate that this product is not currently in the cart, and that you need to create a CartItem object for it.

The Total comes last:

Public ReadOnly Property Total() As Double

Get

Dim t As Double

If _items Is Nothing Then

Return 0

End If

For Each Item As CartItem In _items

t += Item.LineTotal

Next

Return t

End Get

End Property

It’s a fairly simple property too. If there are no items in your collection (you check this by seeing if it Is Nothing) then you don’t have any arithmetic to do. Otherwise, you iterate through each Item in the CartItem collection, adding the LineTotal property on for that item and you return the total amount as the variable t.

The Profile

You have your WroxShoppingCart object, which will act as the memory of the shopping cart, but this still doesn’t answer a key question — how are you going to keep this shopping cart if your user gets his Internet connection violently terminated? In fact you’ve already looked at the solution to this in a previous chapter.

In Chapter 11 you looked at how you can create a user profile and how it can be used to create a particular personalized view of the site for any user who logs on to the site. In particular, you stored the member’s name, address (including city, county, and country), e-mail, whether he wanted to receive mailings or not, and his particular theme of the site. It is via this capability that you can also store the ShoppingCart object. Rather than getting you to create the whole profile, we’ve already provided it in the ready-to-go app that is available for download from www.wrox.com for this chapter.

I can hear the wiseguys at the back now — so I see how to save the cart, but surely you still have to log in to get associated with your cart? That’s where the wiseguys are wrong. Another great new feature of ASP.NET is the capability to track seemingly anonymous users via the personalization and profiling system. If the wiseguys had been paying attention in Chapter 11, they would have known that!

490

E-Commerce

In Chapter 11 you saw how you could set up a template to handle anonymous users, and how you could also migrate the details from the anonymous person’s shopping cart to the bona fide logged-in user’s shopping cart. Now it’s time to fill in the other jigsaw pieces. How does this fit into the overall shopping cart picture?

Well, you can set an attribute to track anonymous users so that even if they haven’t logged in, and have their connection to the application terminated, then when they come back they will still have their shopping cart contents intact. This is all contained within the Web.config file, which you have already partially predefined for the application in this chapter, so that your e-commerce application makes use of changes introduced to the Wrox United site in Chapter 11, and therefore requires a minimal amount of extra code. You add that capability in the next Try It Out.

Try It Out

Amending the Profile to Use the ShoppingCart Object

1.In the Chapter13 application, go to Solution Explorer and open up the Web.config file. Scroll down to find the <profile> element and add the highlighted code:

<anonymousIdentification enabled=”True”> <profile enabled=”true”>

<properties>

<add name=”MemberName”/> <add name=”Name”/>

<add name=”Address”/> <add name=”City”/> <add name=”County”/> <add name=”PostCode”/> <add name=”Country”/>

<add name=”Mailings” type=”System.Boolean”/> <add name=”Email”/>

<add name=”Theme”/>

<add name=”Cart” serializeAs=”Binary” type=”Wrox.Commerce.WroxShoppingCart” allowAnonymous=”true”/>

</properties>

</profile>

2.Save Web.config.

How It Works

Because Web.config is used by your application, the simple act of saving any changes ensures that the update is immediately applied. You’ve only added two items. The first just switches on anonymous identification, which is switched off by default:

<anonymousIdentification enabled=”True”>

The second is the cart definition:

<add name=”Cart” serializeAs=”Binary” type=”Wrox.Commerce.WroxShoppingCart” allowAnonymous=”true”/>

491

Chapter 13

You use the Type attribute to refer to the ShoppingCart object. You set the allowAnonymous attribute to true so that this particular property is tracked even when the user hasn’t logged in. Last, there is a bit of technical detail in the serializeAs property, which needn’t concern you. It simply enables you to make use of your ShoppingCart object. You can find more details about it at http://msdn2

.microsoft.com/library/46xzk8kd(en-us,vs.80).aspx.

The Shopping Cart Control

Unfortunately, among the multitude of new controls, there is no predefined shopping cart control that you can use, so you are going to have to create one. However, what you can do is make use of some of the existing ASP.NET 2.0 controls and you can construct a shopping cart control that you can not just use in this application, but in any application you come to build. In ASP.NET 2.0, the data handling features have taken a giant leap forward, and you can use the GridView control and some clever data-binding to create your shopping cart for you.

Before you rush into building the cart, though, it’s worth thinking a little bit more about design. How are you going to access your cart? How are you going to display the items in it? The first question is easy enough to answer: You add a button to your product item page, which when clicked simply adds the item to the cart. However, where should you go then? Rather than going to your shopping cart, you probably want to return to your catalog. Shopping carts by nature should be unobtrusive; you don’t want to be confronted with the contents of your cart every time you stick an item in; this is probably not conducive to impulse buying (and by inference profitable selling)! It’s much easier only to be confronted with the contents once you get to checkout. So your system develops a structure like Figure 13-19.

Shopping Cart

Product Catalog

Product Item

Add an Item

Figure 13-19

This diagram shows how you can navigate between the different parts of your application. You can move from the Product Catalog page, either to the Shopping Cart itself or to the Product Item page. From the Product Item page you can Add an Item, which in turn will appear in the Shopping Cart.

The second question, then, is about how you should display your shopping cart. If you were feeling extremely confident about the layout, you could probably have a little control pop up at the side that appeared in every page of the site, but because you don’t want to have to spend a lot of time with the jigsaw puzzle of fitting things into your web site design, you’ll just make the shopping cart a separate page that can be easily accessed via a separate link. You’ve already earmarked the GridView control to display the contents of your cart, so continue and build the next stage of your pipeline.

In this Try It Out, you create a user control, the Shopping Cart control, and then add it to a page. The user control is a lot more portable; you learned about them in Chapter 10 and how they help you to reuse code effectively.

492

E-Commerce

Try It Out

Adding a Shopping Cart Control

1.Open Solution Explorer in Visual Web Developer. Right-click the top item and select Add New Item. Add a Web User Control and call it WroxShoppingCart.ascx.

2.In Design View, select the GridView control from the Data section of the Toolbox. Click the smart tag dialog box and select the Edit Columns option.

3.From the dialog that appears, select one TemplateField, four BoundFields, and one CommandField, as shown in Figure 13-20.

Figure 13-20

These will be used to represent the ProductImage, ProductName, Quantity, Price, and LineTotal (that is, quantity multiplied by price) of that particular item and a button to edit that item or to delete it from your shopping cart, respectively.

4.Select the BoundFields field and change the properties one by one in the Properties window as follows:

 

DataField

HeaderText

ReadOnly

DataFormatString

 

 

 

 

 

Bound Field 1

ProductName

Product

True

 

Bound Field 2

Quantity

Quantity

False

 

Bound Field 3

Price

Price

True

{0:c}

Bound Field 4

LineTotal

Total

True

{0:c}

 

 

 

 

 

Don’t click OK in between adding each item, which will take you back to Design View.

493

Chapter 13

5.Go to the CommandField and set the ShowEditButton and ShowDeleteButton properties to

True.

6.Click OK to go back to Design View. Click the smart tag dialog box, and select Edit Templates from the flyout that appears.

7.Now drop an Image control into the ItemTemplate and click the smart tag dialog box, as displayed in Figure 13-21.

Figure 13-21

8.Select Edit Data Bindings and select ImageUrl from the Bindable properties. Add the following code to the Code Expression box:

Eval(“ProductImageUrl”, “~/ProductImages/thumb_{0}”)

9.Return to Design View and select the smart tag dialog box on the GridView control. Select Edit Templates EmptyDataTemplate from the menu that appears. Type the following text directly into the EmptyDataTemplate (see Figure 13-22): There is nothing in your shopping cart. You can buy items from the Shop.

Figure 13-22

Drop back to Source view and add an anchor <a> tag around the Shop section as follows:

<a href=”Wroxshop.aspx”>Shop</a>.

This is the text that will be displayed when the user views a shopping cart with no items in it. You supply a link back to the main shopping page as well.

10.Choose to End Template Editing from the Common Tasks panel

11.In Design View right-click the GridView control and select Properties. Enter the following values:

494

E-Commerce

Property

Value

(ID)

CartGrid

AutoGenerateColumns

False

DataKeyNames

ProductID

12.Right-click Solution Explorer and select Add a New Item. Select a Web Form and call the new item WroxShoppingCartPage.aspx. Note that this is an .aspx file now unlike the user control you have just created. This is the page that will host your user control.

13.In Design View, drag WroxShoppingCart.ascx onto the page, as shown in Figure 13-23.

Figure 13-23

How It Works

This finishes the first stage of your shopping cart control. You’ve created your control and you’ve added a thumbnail image and fields to store the Quantity, Price, and LineTotal of the product, as well as a button enabling you to edit or delete your choices in the cart.

If you go to Source View it will currently look as follows:

495

Chapter 13

<asp:GridView ID=”CartGrid” Runat=”server” AutoGenerateColumns=”False” DataKeyNames=”ProductID” >

<Columns>

<asp:TemplateField>

<ItemTemplate>

<asp:Image id=”ProductImage” Runat=”server” ImageUrl=’<%# Eval(“ProductImageURL”, “~/ProductImages/thumb_{0}”)%>’ />

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField DataField=”ProductName” HeaderText=”Product” ReadOnly=”True” />

<asp:BoundField DataField=”Quantity” HeaderText=”Quantity” />

<asp:BoundField DataField=”Price” HeaderText=”Price” DataFormatString=”{0:c}” ReadOnly=”True” /> <asp:BoundField DataField=”LineTotal” HeaderText=”Total” DataFormatString=”{0:c}” ReadOnly=”True” /> <asp:CommandField ShowEditButton=”True” ShowDeleteButton=”true”></asp:CommandField>

</Columns>

<EmptyDataTemplate>

There is nothing in your shopping cart. You can buy items from the <a href=”wroxshop.aspx”>Shop</a>.

</EmptyDataTemplate>

</asp:GridView>

This is all very familiar and close to what you supplied to the DataList controls in your Catalog and Item pages. You bind the ProductImageURL to an image in the ItemTemplate. You have several bound fields that will display text. The price fields have settings for the DataFormatString so that they display their values correctly as prices. However, there is one setting to note. In your bound fields, you made three of the four rows read-only. The Quantity row was left editable so that you can edit the contents of your cart.

You’ve also added an EmptyDataTemplate to display a message in the event that there is nothing in the cart. However, at the moment, you have no data source. In the Catalog and Item pages, you first created a SqlDataSource control and bound it to the DataList control; you haven’t bound the ShoppingCart control to anything yet.

Automating the Shopping Cart

So far, so good, you have your ShoppingCart control fully designed. However, it doesn’t do much at the moment. In fact, it doesn’t do anything! If you want the cart to be responsive, you will need to add some code telling ASP.NET 2.0 what to do when something occurs. When you created your bound fields in the shopping cart, three of the four bound fields were read-only; the last-one, Quantity, was the only bound field left editable because it means that you only need to anticipate what happens if someone changes the quantity of items within a particular row in the cart.

You will want to cater to four possible events, because there are four possible scenarios:

Editing the cart: When you enter a new quantity.

Canceling an edit in the cart: When you decide you don’t want go with the quantity value you’ve changed.

Updating the cart: When you want that new quantity to take effect.

Deleting items from the cart: When you want to completely remove an item from the cart.

496

E-Commerce

This will require some code-behind. You looked at code-behind in Chapters 9 and 10. Here your code-behind will be run directly in response to one of these four events occurring. A second question is once you’ve updated the shopping cart, how do you associate that with a particular user? You’ve already created a profile, so now all you need to do is to reference that profile within your code, via the Profile object.

Go ahead and add this code to your shopping cart in the next Try It Out.

Try It Out

Automating the Shopping Cart

1.Go to your ShoppingCart control (right-click GridView and select Properties. From the Properties window, select the Lightning Bolt button the fourth one along, as shown in Figure 13-24).

Figure 13-24

2.This displays a list of events. Double-click the RowEditing event. In Source View, a gap will have appeared for the events. Add the following highlighted code to the events:

Sub CartGrid_RowEditing(ByVal sender As Object, ByVal e As

System.Web.UI.WebControls.GridViewEditEventArgs)

CartGrid.EditIndex = e.NewEditIndex

BindGrid()

End Sub

3.Go back to Design View, right-click GridView, and select Properties. It should take you straight to Events this time. Double-click the RowUpdating event. Add the following highlighted code:

Sub CartGrid_RowUpdating(ByVal sender As Object, ByVal e As

System.Web.UI.WebControls.GridViewUpdateEventArgs)

Dim QuantityTextBox As TextBox = _

CType(CartGrid.Rows(e.RowIndex).Cells(2).Controls(0), TextBox)

Dim Quantity As Integer = Convert.ToInt32(QuantityTextBox.Text)

If Quantity = 0 Then

Profile.Cart.Items.RemoveAt(e.RowIndex)

Else

Profile.Cart.Items(e.RowIndex).Quantity = Quantity

End If

CartGrid.EditIndex = -1

BindGrid()

End Sub

4.Go back to Design View. Right-click GridView and select Properties. Double-click the RowCancelingEdit event. Add the highlighted code:

Sub CartGrid_RowCancelingEdit(ByVal sender As Object, ByVal e As

System.Web.UI.WebControls.GridViewCancelEditEventArgs)

CartGrid.EditIndex = -1

BindGrid()

End Sub

497

Chapter 13

5.In Design View, right-click GridView and select Properties. Double-click the RowDeleting event. Add the highlighted code:

Sub CartGrid_RowDeleting(ByVal sender As Object, ByVal e As

System.Web.UI.WebControls.GridViewDeleteEventArgs)

Profile.Cart.Items.RemoveAt(e.RowIndex)

BindGrid()

End Sub

6.From Design View, double-click the blank page surrounding the WroxShoppingCart control, and add the highlighted code to the Page_Load event:

Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Profile.Cart Is Nothing Then

Return End If

If Not Page.IsPostBack Then BindGrid()

End If

If Profile.Cart.Items.Count = 0 Then TotalLabel.Visible = False

End If End Sub

7.You may have noticed that you’ve also referenced a function called BindGrid()within all of these events. This function does the binding so that your shopping cart can display something. You need to add this code for BindGrid() underneath the functions within the code-behind as well:

Private Sub BindGrid()

CartGrid.DataSource = Profile.Cart.Items

DataBind()

TotalLabel.Text = String.Format(“Total:{0,19:C}”, Profile.Cart.Total)

End Sub

8.At the top of the page add a reference to your WroxShoppingCart object:

<%@ Import Namespace=”Wrox.Commerce” %>

9.Switch to Design View and drag a Label control onto the screen and place it under the GridView control. Right-click the Label control and select Properties. Delete the Text property and change the ID property to TotalLabel, as shown in Figure 13-25.

498