Để hiểu về giỏ hàng thì chúng ta hãy tưởng tượng chúng ta đang đi siêu thị nhé. Việc đầu tiên khi bạn vào siêu thị là bạn làm gì? Tôi chắc rằng bạn sẽ cần tới một chiếc xe đẩy để chở hàng, hay một cái giỏ để đựng hàng, tôi xin tạm gọi hai thứ đó là “giỏ hàng”. Công việc tiếp theo là lựa chọn sản phẩm để mua, bạn có thể nhặt sản phẩm định mua, đưa vào giỏ hàng, mua bao nhiêu sản phẩm thì bạn nhặt bấy nhiêu. Sau khi nhặt một hồi, bạn có thể thay đổi ý định, bỏ bớt một số sản phẩm, hoặc giảm hoặc tăng số lượng sản phẩm mình mua trong giỏ hàng. Những sản phẩm trong giỏ hàng là những sản phẩm bạn chọn để mua, và nó chỉ có tính chất lưu trữ tạm thời trước khi thanh toán. Tức là, khi bạn thanh toán xong giỏ hàng lại trở về trạng thái rỗng.
Câu chuyện về giỏ hàng trong website thương mại điện tử, nó cũng giống như chiếc xe đẩy chở hàng trong siêu thị. Tức là, bạn phải làm sao cho người dùng lựa chọn được sản phẩm, đưa vào giỏ hàng, thay đổi số lượng sản phẩm, xóa sản phẩm trong giỏ hàng. Và bạn nhớ rằng giỏ hàng chỉ là nơi lưu trữ tạm thời các sản phẩm mà bạn cần mua trước khi thanh toán.
Tôi thấy có khá nhiều bạn sinh viên đau đầu với bài toán kinh điển này. Để giúp các bạn bớt đau đầu, tôi sẽ hướng dẫn các bạn những thao tác cơ bản để xây dựng được giỏ hàng trong ASP.NET.
Để tạo ra được giỏ hàng, chúng ta cần có 3 class cơ bản là ShoppingCart, CartItem, Product được mô tả như class diagram ở dưới đây.
Bước 1: Tạo Class ShoppingCart
Chúng
 ta cần một nơi để lưu trữ trữ các mục (item) trong giỏ hàng cũng như 
cung cấp chức năng để thao tác với những phần tử đó. Chúng ta sẽ tạo ra 
một class để làm được việc này. Class này sẽ quản lý việc lưu trữ 
session (phiên làm việc).Đầu tiên, chúng ta phải tạo ra thư mục App_Code. Để làm được việc này, vào menu “Website”, sau đó chọn “Add ASP.NET Folder”, rồi chọn “App_Code”. Đây chính là nơi chúng ta đặt toàn bộ class do mình viết ra. Từ bất kỳ trang web nào cũng có thể truy cập tới code trong App_Code (chúng ta không cần phải tham chiếu tới nó bằng cách sử dụng những lệnh kiểu như “include” hay bất cứ cái gì). Sau đó, chúng ta có thể thêm class vào thư mục này bằng cách kích chuột phải vào folder rồi chọn “Add New Item”.
Mẹo nhanh: Regions (Khu vực) trong ASP.NET thực sự là một điều tuyệt vời để tổ chức và nhóm code lại với nhau. Điều tốt đẹp nhất về chúng là bạn có thể mở và đóng các khu vực để thu gọn số lượng mã mà bạn đang tìm kiếm hoặc nhanh chóng tìm thấy theo cách của bạn xung quanh một tập tin.
Đây là code của ShoppingCart
| 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 | usingSystem.Collections.Generic;usingSystem.Web;/*** The ShoppingCart class** Holds the items that are in the cart and provides methods for their manipulation*/publicclassShoppingCart {#region PropertiespublicList Items { get; privateset; }#endregion#region Singleton Implementation// Readonly properties can only be set in initialization or in a constructorpublicstaticreadonlyShoppingCart Instance;// The static constructor is called as soon as the class is loaded into memorystaticShoppingCart() {// If the cart is not in the session, create one and put it there// Otherwise, get it from the sessionif(HttpContext.Current.Session["ASPNETShoppingCart"] == null) {Instance = newShoppingCart();Instance.Items = newList();HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;} else{Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];}}// A protected constructor ensures that an object can't be created from outsideprotectedShoppingCart() { }#endregion#region Item Modification Methods/*** AddItem() - Adds an item to the shopping*/publicvoidAddItem(intproductId) {// Create a new item to add to the cartCartItem newItem = newCartItem(productId);// If this item already exists in our list of items, increase the quantity// Otherwise, add the new item to the listif(Items.Contains(newItem)) {foreach(CartItem item inItems) {if(item.Equals(newItem)) {item.Quantity++;return;}}} else{newItem.Quantity = 1;Items.Add(newItem);}}/*** SetItemQuantity() - Changes the quantity of an item in the cart*/publicvoidSetItemQuantity(intproductId, intquantity) {// If we are setting the quantity to 0, remove the item entirelyif(quantity == 0) {RemoveItem(productId);return;}// Find the item and update the quantityCartItem updatedItem = newCartItem(productId);foreach(CartItem item inItems) {if(item.Equals(updatedItem)) {item.Quantity = quantity;return;}}}/*** RemoveItem() - Removes an item from the shopping cart*/publicvoidRemoveItem(intproductId) {CartItem removedItem = newCartItem(productId);Items.Remove(removedItem);}#endregion#region Reporting Methods/*** GetSubTotal() - returns the total price of all of the items* before tax, shipping, etc.*/publicdecimalGetSubTotal() {decimalsubTotal = 0;foreach(CartItem item inItems)subTotal += item.TotalPrice;returnsubTotal;}#endregion} | 
Bước 2: Tạo class CartItem và Product
Bên 
cạnh việc tạo ra một nơi để lưu trữ các phần tử, chúng ta cũng cần tạo 
ra nơi để lưu trữ thông tin về mỗi mục (item). Chúng ta sẽ tạo ra class 
CartItem để làm việc này. Chúng ta cũng sẽ tạo ra một class Product đơn 
giản, nó sẽ chứa thông tin cơ bản về sản phẩm chúng ta đang bán.Đây là CartItem class
| 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 | usingSystem;/** * The CartItem Class * * Basically a structure for holding item data */publicclassCartItem : IEquatable<CartItem> {    #region Properties    // A place to store the quantity in the cart    // This property has an implicit getter and setter.    publicintQuantity { get; set; }    privateint_productId;    publicintProductId {        get{ return_productId; }        set{            // To ensure that the Prod object will be re-created            _product = null;            _productId = value;        }    }    privateProduct _product = null;    publicProduct Prod {        get{            // Lazy initialization - the object won't be created until it is needed            if(_product == null) {                _product = newProduct(ProductId);            }            return_product;        }    }    publicstringDescription {        get{ returnProd.Description; }    }    publicdecimalUnitPrice {        get{ returnProd.Price; }    }    publicdecimalTotalPrice {        get{ returnUnitPrice * Quantity; }    }    #endregion    // CartItem constructor just needs a productId    publicCartItem(intproductId) {        this.ProductId = productId;    }    /**     * Equals() - Needed to implement the IEquatable interface     *    Tests whether or not this item is equal to the parameter     *    This method is called by the Contains() method in the List class     *    We used this Contains() method in the ShoppingCart AddItem() method     */    publicboolEquals(CartItem item) {        returnitem.ProductId == this.ProductId;    }} | 
Đây là Product class
| 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 | /** * The Product class * * This is just to simulate some way of accessing data about  our products */publicclassProduct{    publicintId { get; set; }    publicdecimalPrice { get; set; }    publicstringDescription { get; set; }    publicProduct(intid)    {        this.Id = id;        switch(id) {            case1:                this.Price = 19.95m;                this.Description = "Shoes";                break;            case2:                this.Price = 9.95m;                this.Description = "Shirt";                break;            case3:                this.Price = 14.95m;                this.Description = "Pants";                break;        }    }} | 
Một “property” (thuộc tính) là một biến trong một class mà nó kèm theo setter, getter hoặc cả hai. Trong class Product chúng ta khai báo các thuộc tính của sản phẩm thông qua các property: Id, Price, Description. Ngoài ra, class Product còn khởi tạo một vài sản phẩm (3 sản phẩm) để chúng ta dễ dàng kiểm tra phần giỏ hàng.
Bước 3: Thêm vào giỏ hàng
Sau khi
 code rất nhiều, giờ là lúc chúng ta làm cái gì đó thật trực quan. Chúng
 ta sẽ tạo ra một page đơn giản để thêm các mục vào trong giỏ hàng. Tất 
cả, chúng ta có một vài mục cùng với link “Add to Cart” . Nào chúng ta 
hãy cùng code trang Default.aspx.Đây phần design của trang Default.aspx
| 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 | <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><headrunat="server">    <title>My Store</title>    <linkhref="Styles/StyleSheet.css"rel="stylesheet"type="text/css"/></head><body>    <formid="form1"runat="server">        <divclass="container">            <h1>My Store</h1>            <divclass="products">                <div>Shoes - <asp:LinkButtonrunat="server"ID="btnAddShirt"OnClick="btnAddShoes_Click">Add To Cart</asp:LinkButton></div>                <div>Shirt - <asp:LinkButtonrunat="server"ID="btnAddShorts"OnClick="btnAddShirt_Click">Add To Cart</asp:LinkButton></div>                <div>Pants - <asp:LinkButtonrunat="server"ID="btnAddShoes"OnClick="btnAddPants_Click">Add To Cart</asp:LinkButton></div>            </div>            <ahref="ViewCart.aspx">View Cart</a>        </div>    </form></body></html> | 
Còn đây là phần code behind để xử lý các sự kiện Default.aspx.cs
| 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 | usingSystem;publicpartialclass_Default : System.Web.UI.Page {    protectedvoidPage_Load(objectsender, EventArgs e) {    }    protectedvoidbtnAddShoes_Click(objectsender, EventArgs e) {        // Add product 1 to the shopping cart        ShoppingCart.Instance.AddItem(1);        // Redirect the user to view their shopping cart        Response.Redirect("ViewCart.aspx");    }    protectedvoidbtnAddShirt_Click(objectsender, EventArgs e) {        ShoppingCart.Instance.AddItem(2);        Response.Redirect("ViewCart.aspx");    }    protectedvoidbtnAddPants_Click(objectsender, EventArgs e) {        ShoppingCart.Instance.AddItem(3);        Response.Redirect("ViewCart.aspx");    }} | 
Bước 4: Hiển thị giỏ hàng
Tất cả những gì chúng ta làm ở trên chỉ là để chuẩn bị cho shopping cart! Giờ chúng ta hãy nhìn trang ViewCart.aspx.Đây là code của trang ViewCart.aspx. Về cơ bản chúng ta sẽ sử dụng GridView để hiển thị thông tin trong giỏ hàng. Cột Description trong GridView chúng ta sẽ sử dụng BoundFiled. Còn cột Quantity chứa số lượng sản phẩm sẽ mua, ta cần sử dụng TemplateFiled, để có thể đưa TextBox và link Remove luôn vào đó. Để hiển thị thông tin như Price, Description …. trên GridView chúng ta cần dùng tới <%# Eval(“PropertyName”) %>.
Chi tiết code của ViewCart.aspx ở đây
| 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 | <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ViewCart.aspx.cs" Inherits="ViewCart" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><headrunat="server">    <title>Shopping Cart</title>    <linkhref="Styles/StyleSheet.css"rel="stylesheet"type="text/css"/></head><body>    <formid="form1"runat="server">        <divclass="container">            <h1>Shopping Cart</h1>            <ahref="Default.aspx">< Backto Products</a>            <br/><br/>            <asp:GridViewrunat="server"ID="gvShoppingCart"AutoGenerateColumns="false"EmptyDataText="There is nothing in your shopping cart."GridLines="None"Width="100%"CellPadding="5"ShowFooter="true"DataKeyNames="ProductId"OnRowDataBound="gvShoppingCart_RowDataBound"OnRowCommand="gvShoppingCart_RowCommand">                <HeaderStyleHorizontalAlign="Left"BackColor="#3D7169"ForeColor="#FFFFFF"/>                <FooterStyleHorizontalAlign="Right"BackColor="#6C6B66"ForeColor="#FFFFFF"/>                <AlternatingRowStyleBackColor="#F8F8F8"/>                <Columns>                    <asp:BoundFieldDataField="Description"HeaderText="Description"/>                    <asp:TemplateFieldHeaderText="Quantity">                        <ItemTemplate>                            <asp:TextBoxrunat="server"ID="txtQuantity"Columns="5"Text='<%# Eval("Quantity") %>'></asp:TextBox><br/>                            <asp:LinkButtonrunat="server"ID="btnRemove"Text="Remove"CommandName="Remove"CommandArgument='<%# Eval("ProductId") %>' style="font-size:12px;"></asp:LinkButton>                        </ItemTemplate>                    </asp:TemplateField>                    <asp:BoundFieldDataField="UnitPrice"HeaderText="Price"ItemStyle-HorizontalAlign="Right"HeaderStyle-HorizontalAlign="Right"DataFormatString="{0:C}"/>                    <asp:BoundFieldDataField="TotalPrice"HeaderText="Total"ItemStyle-HorizontalAlign="Right"HeaderStyle-HorizontalAlign="Right"DataFormatString="{0:C}"/>                </Columns>            </asp:GridView>            <br/>            <asp:Buttonrunat="server"ID="btnUpdateCart"Text="Update Cart"OnClick="btnUpdateCart_Click"/>        </div>    </form></body></html> | 
Kết quả
Bây giờ, chúng ta đã có một shopping cart khá là đẹp mắt !Bài này mới chỉ dừng lại ở việc hướng dẫn bạn xây dựng giỏ hàng bằng ASP.NET sử dụng C#, nhưng từ đây bạn hoàn toàn có thể thể triển khai cách làm này với các ngôn ngữ khác. Chúc bạn thành công với những website thương mại điện tử của mình !
 
 
No comments:
Post a Comment