電子商務網站 ─ 購物車動作原理【下】
本文摘錄自旗標 F8927「ASP.NET Starter Kit 商務網站速成」一書
本期文摘承接上一期(第212期)電子報,「購物車動作原理」的主題介紹,這一次我們繼續探討更新購物車,和最後的步驟「結帳」,這樣就完成了整個購物車的基本功能了。
更新購物車
當更改購物車的商品數量或刪除後,按下 [Update You
r Shopping Cart] 按鈕後將執行UpdateShoppingCartD
atabase() :
================================================
'更新購物車(Shopping Cart)資料庫
Sub UpdateShoppingCartDatabase()
Dim cart As ASPNET.StarterKit.Commerce.ShoppingCartDB = New
ASPNET.StarterKit.Commerce.ShoppingCartDB()
'取得使用者的shopping cart ID
Dim cartId As String = cart.GetShoppingCartId()
'循環取得購物車商品明細
Dim i As Integer
For i = 0 To MyList.Items.Count - 1
'取得row's controls references
Dim quantityTxt As TextBox = CType(MyList.Items(i).
FindControl("Quantity"), TextBox)
Dim remove As CheckBox = CType(MyList.Items(i).
FindControl("Remove"),CheckBox)
Dim quantity As Integer
Try
quantity = CInt(quantityTxt.Text)
'若數量有變動, 或勾選刪除
If quantity <> CInt(MyList.DataKeys(i)) Or remove.Checked
= True Then
Dim lblProductID As Label =
CType(MyList.Items(i).FindControl("ProductID"), Label)
If quantity = 0 Or remove.Checked = True Then
'若數量為0, 或勾選刪除則移除此項目
cart.RemoveItem(cartId, CInt(lblProductID.Text))
Else
'更新項目
cart.UpdateItem(cartId, CInt(lblProductID.Text),
quantity)
End If
End If
Catch
MyError.Text = "部份輸入有誤."
End Try
Next
End Sub
================================================
結帳
當結帳按下 [Final Check Out] 按鈕後將執行Checkou
tBtn_Click (),首先執行UpdateShoppingCartDatabas
e先更新購物車,再導向結帳Checkout.aspx程式:
================================================
Private Sub CheckoutBtn_Click(ByVal sender As Object, ByVal e
As System.Web.UI.ImageClickEventArgs) Handles CheckoutBtn.
Click'更新購物車(Shopping Cart)
UpdateShoppingCartDatabase()
Dim cart As ASPNET.StarterKit.Commerce.ShoppingCartDB = New
ASPNET.StarterKit.Commerce.ShoppingCartDB()
'計算shopping cart ID
Dim cartId As String = cart.GetShoppingCartId()
'若購物車不是空的, 則導向買單(checkout)網頁
If cart.GetItemCount(cartId) <> 0 Then
Response.Redirect("Checkout.aspx")
Else
MyError.Text = "購物車是空的, 不能買單."
End If
End Sub
================================================
結帳Checkout.aspx程式,包括DataGrid控制項:
================================================
<asp:DataGrid id="MyDataGrid" width="90%" BorderColor="Black"
GridLines="Vertical" cellpadding="4" Font-Name="Verdana"
Font-Size="8pt"ShowFooter="True"
HeaderStyle-CssClass="CartListHead"
FooterStyle-CssClass="cartlistfooter"
ItemStyle-CssClass="CartListItem"
AlternatingItemStyle-CssClass="CartListItemAlt"
AutoGenerateColumns="False"
runat="server" Font-Names="Verdana">
<AlternatingItemStyle CssClass="CartListItemAlt">
</AlternatingItemStyle>
<ItemStyle CssClass="CartListItem"></ItemStyle>
<HeaderStyle CssClass="CartListHead"></HeaderStyle>
<FooterStyle CssClass="cartlistfooter"></FooterStyle>
<Columns>
<asp:BoundColumn DataField="ModelName" HeaderText="產品名
稱"></asp:BoundColumn>
<asp:BoundColumn DataField="ModelNumber" HeaderText="型號號
碼"></asp:BoundColumn>
<asp:BoundColumn DataField="Quantity" HeaderText="數
量"></asp:BoundColumn>
<asp:BoundColumn DataField="UnitCost" HeaderText="價格"
DataFormatString="{0:c}"></asp:BoundColumn>
<asp:BoundColumn DataField="ExtendedAmount" HeaderText="小
計"DataFormatString="{0:c}"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
================================================
當網頁載入時將執行Page_Load(),ShoppingCartDB.vb
的GetItems () 執行預存程序CMRC_ShoppingCartList
,取得購物車資料庫的資料從資料庫的CMRC_ShoppingC
art資料表取得購物車的資料後,再資料繫結ModelName
(產品名稱)、ModelNumber(型號)、Quantity(數
量)、UnitCost(價格)欄位到DataList控制項顯示結
帳清單:
================================================
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
If Page.IsPostBack = False Then
'取得shopping cart ID
Dim cart As ASPNET.StarterKit.Commerce.ShoppingCartDB = New
ASPNET.StarterKit.Commerce.ShoppingCartDB()
Dim cartId As String = cart.GetShoppingCartId()
'結帳商品列表
MyDataGrid.DataSource = cart.GetItems(cartId)
MyDataGrid.DataBind()
'更新總金額
TotalLbl.Text = String.Format("{0:c}", cart.GetTotal
(cartId))
End If
End Sub
================================================
當結帳按下 [Submit] 按鈕後將執行SubmitBtn_Click
(),執行PlaceOrder()下訂單:
================================================
Private Sub SubmitBtn_Click(ByVal sender As Object, ByVal e As
System.Web.UI.ImageClickEventArgs) Handles SubmitBtn.Click
Dim cart As ASPNET.StarterKit.Commerce.ShoppingCartDB = New
ASPNET.StarterKit.Commerce.ShoppingCartDB()
'取得shopping cart ID
Dim cartId As String = cart.GetShoppingCartId()
'取得customerID
Dim customerId As String = User.Identity.Name
If (Not cartId Is Nothing) And (Not customerId Is Nothing)
Then'下訂單(Place the order)
Dim ordersDatabase As ASPNET.StarterKit.Commerce.OrdersDB =
New ASPNET.StarterKit.Commerce.OrdersDB()
Dim orderId As Integer = ordersDatabase.PlaceOrder(
customerId,cartId)
Header.Text = "結帳完畢(Check Out Complete)!"
------------------------------------------------
Message.Text = "<b>您的訂單代號(Order Number)為: </b>" &
orderId
SubmitBtn.Visible = False
End If
End Sub
================================================
OrdersDB.vb的PlaceOrder () 執行預存程序CMRC_Orde
rsAdd:
================================================
Public Function PlaceOrder(ByVal customerID As String, ByVal
cartID As String) As Integer
'由Web.Config取得資料庫連線字串, 設定預存程序名稱
Dim myConnection As SqlConnection = New SqlConnection
(ConfigurationSettings.AppSettings("ConnectionString"))
Dim myCommand As SqlCommand =
New SqlCommand("CMRC_OrdersAdd",myConnection)
'設定命令為預存程序
myCommand.CommandType = CommandType.StoredProcedure
'輸入預存程序輸入參數值
Dim parameterCustomerID As SqlParameter = New SqlParameter
("@CustomerID", SqlDbType.Int, 4)
parameterCustomerID.Value = CInt(customerID)
myCommand.Parameters.Add(parameterCustomerID)
Dim parameterCartID As SqlParameter = New SqlParameter(
"@CartID", SqlDbType.NVarChar, 50)
parameterCartID.Value = cartID
myCommand.Parameters.Add(parameterCartID)
Dim parameterShipDate As SqlParameter = New SqlParameter(
"@ShipDate", SqlDbType.DateTime, 8)
parameterShipDate.Value = CalculateShippingDate(customerID
, cartID)
myCommand.Parameters.Add(parameterShipDate)
Dim parameterOrderDate As SqlParameter = New SqlParameter(
"@OrderDate", SqlDbType.DateTime, 8)
parameterOrderDate.Value = DateTime.Now
myCommand.Parameters.Add(parameterOrderDate)
'預存程序輸出參數
-----------------------------------------------
Dim parameterOrderID As SqlParameter = New SqlParameter(
"@OrderID", SqlDbType.Int, 4)
parameterOrderID.Direction = ParameterDirection.Output
myCommand.Parameters.Add(parameterOrderID)
'連線資料庫並執行預存程序
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
'傳回OrderID
Return CInt(parameterOrderID.Value)
End Function
================================================
預存程序CMRC_OrdersAdd,首先新增資料到訂單資料表
CMRC_Orders,接著複製購物車資料到訂單明細資料表C
MRC_OrderDetails,最後移除購物車資料:
================================================
CREATE Procedure CMRC_OrdersAdd
(
@CustomerID int,
@CartID nvarchar(50),
@OrderDate datetime,
@ShipDate datetime,
@OrderID int OUTPUT
)
AS
BEGIN TRAN AddOrder
/* 新增資料到訂單資料表CMRC_Orders */
INSERT INTO CMRC_Orders(CustomerID, OrderDate, ShipDate)
VALUES(@CustomerID, @OrderDate, @ShipDate)
SELECT @OrderID = @@Identity
/* 複製購物車資料到訂單明細資料表CMRC_OrderDetails */
INSERT INTO CMRC_OrderDetails(OrderID, ProductID, Quantity,
UnitCost)
SELECT @OrderID, CMRC_ShoppingCart.ProductID,
Quantity, CMRC_Products.UnitCost
FROM CMRC_ShoppingCart
-----------------------------------------------
INNER JOIN CMRC_Products ON CMRC_ShoppingCart.ProductID =
CMRC_Products.ProductID
WHERE CartID = @CartID
/* 移除購物車資料 */
EXEC CMRC_ShoppingCartEmpty @CartID
COMMIT TRAN AddOrder
GO
================================================
學會了嗎?
--- 本篇完
|