Thứ Năm, 4 tháng 8, 2016

Hướng dẫn tạo ứng dụng Giỏ hàng

Hướng dẫn tạo ứng dụng Giỏ hàng (Shopping Cart) trong ASP.NET MVC bằng kỹ thuật xử lý Ajax và quản lý bằng Session

Keyword: giỏ hàng asp net mvc, giỏ hàng ajax, ứng dụng giỏ hàng asp mvc, tạo giỏ hàng bằng ajax, ajax, giỏ hàng
Hướng dẫn tạo ứng dụng Giỏ hàng (Shopping Cart) trong ASP.NET MVC bằng kỹ thuật xử lý Ajax và quản lý bằng Session
Bài viết này tôi xin giới thiệu kỹ thuật xử lý Ajax và dùng Session để quản lý ứng dụng giỏ hàng trong các trang mua bán hàng hóa.
Trang mua hàng
giỏ hàng asp mvc ajax

Trang chi tiết giỏ hàng

giỏ hàng asp mvc ajax
Phần này được viết nối tiếp theo series bài lab thực hành ASP.NET MVC cơ bản.
Sau khi bạn đã có trang danh sách Book như hình ở dưới (hoặc một trang danh sách sản phẩm bất kỳ của bạn).

# Step 1: Thêm nút Add To Cart (Mua hàng) ở mỗi dòng sản phẩm và nút Your Orders (sản phẩm đặt mua) như hình ở dưới

Code Thêm Nút giao diện như trên sử dụng bootstrap và lệnh xử lý Javascript
Nút Add To Cart – Người dùng Click vào nút này sẽ xử lý hàm javascript có tên là AddToCart, truyền vào tham số là mã sách của dòng hiện tại. Hàm này bạn sẽ viết ở step 3
?
1
2
3
---
<input type="submit" class="btn btn-danger" onclick="AddToCart('@item.BookId')" value="Add To Cart" />
---
Nút Your Orders
?
1
2
3
4
5
<p class="pull-right">
    <button class="btn btn-warning" type="button" onclick="window.open('/Book/ShoppingCart','_self')" >
        Your Orders <span class="badge" id="Cart_Amount">@ViewBag.count</span>
    </button>
</p>

# Step 2: Viết lớp hỗ trợ xử lý lưu trữ tạm sản phẩm CartItem.

Tạo một model đặt tên là CartItem đặt trong thư mục Models của project với code như sau:
?
1
2
3
4
5
public class CartItem
   {
       public Book productOrder { get; set; }
       public int Quality { get; set; }
   }

# Step 3: Thêm xử lý Ajax đưa sản phẩm vào giỏ hàng, tạo mới một thẻ <script> </script> ở trên đầu của trang mua hàng thêm hàm xử lý javascript như sau:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!--Ajax Process-->
<script>   
    function AddToCart(BookId) {
        $.ajax({
            type: 'POST',
            url: '/Book/AddToCart',
            data: { id: BookId },
            success: function (data) {
                $("#Cart_Amount").html(data.ItemAmount);
            }
        });
    }
</script>
<!--End Ajax Process-->
Lưu ý: Bạn phải khai báo thư viện Jquery trên trang để có thể sử dụng được Ajax

# Step 4: Viết hàm xử lý JsonResult trong BookController để Ajax gọi được theo cấu trúc  url /Book/AddToCart' như sau:

Mở BookController và thêm vào hàm xử lý như sau:
?
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
[HttpPost]
        public JsonResult AddToCart(int id)
        {
            List<CartItem> listCartItem;
            //Process Add To Cart
            if (Session["ShoppingCart"] == null)
            {
                //Create New Shopping Cart Session
                listCartItem = new List<CartItem>();
                listCartItem.Add(new CartItem { Quality = 1, productOrder = db.Books.Find(id) });
                Session["ShoppingCart"] = listCartItem;
            }
            else
            {
                bool flag = false;
                listCartItem = (List<CartItem>)Session["ShoppingCart"];
                foreach (CartItem item in listCartItem)
                {
                    if (item.productOrder.BookId == id)
                    {
                        item.Quality++;
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                    listCartItem.Add(new CartItem { Quality = 1, productOrder = db.Books.Find(id) });
                Session["ShoppingCart"] = listCartItem;
            }
            //Count item in shopping cart
            int cartcount = 0;
            foreach (CartItem item in listCartItem)
            {
                cartcount += item.Quality;
            }
            return Json(new { ItemAmount = cartcount });
        }
Tới bước này bạn đã được kết quả là khi nhấn vào nút Add To Cart của sách thì sách đã được lưu vào giỏ hàng.
Tiếp tới lúc trang web request tới user (ở đây là lúc bạn load trang /Book/getListBook) thì gán giá trị đếm số lượng sản phẩm có trong giỏ hàng, bạn làm như sau: Tại Step 3: Bạn Edit phần javascript ở trên và thêm chuỗi xử lý để gán số lượng sản phẩm trong giỏ hàng xuốngYour Orders như sau:
?
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
<!--Ajax Process-->
@{
        if(Session["ShoppingCart"]!=null)
        {
            int cartcount = 0;
            List<CartItem> ls = (List<CartItem>)Session["ShoppingCart"];
            foreach(CartItem item in ls)
            {
                cartcount += item.Quality;
            }
            ViewBag.count = cartcount;
        }
}
<script>   
    function AddToCart(BookId) {
        $.ajax({
            type: 'POST',
            url: '/Book/AddToCart',
            data: { id: BookId },
            success: function (data) {
                $("#Cart_Amount").html(data.ItemAmount);
            }
        });
    }
</script>
<!--End Ajax Process-->
Tới đây bạn đã hoàn thành bước thêm sản phẩm vào giỏ hàng, hiển thị số lượng sản phẩm trong giỏ hàng lúc load trang. Bước kế tiếp bạn sẽ xây dựng trang hiển thị danh sách giỏ hàng và mua hàng.
Bạn xem nút Your Orders ở bước trên có dòng code như sau:
?
1
2
3
4
5
<p class="pull-right">
    <button class="btn btn-warning" type="button" onclick="window.open('/Book/ShoppingCart','_self')" >
        Your Orders <span class="badge" id="Cart_Amount">@ViewBag.count</span>
    </button>
</p>
Tại nút này có xử lý thêm một sự kiện lúc nhấn vào sẽ mở ra trang ShoppingCart (onlick = window.open(‘Book/ShoppingCart’,’_self). Vậy bạn sẽ viết một hàm trả về View ShoppingCart trong BookController như sau
?
1
2
3
4
public ActionResult ShoppingCart()
        {
            return View();
        }
Lúc này bạn nhấn chuột phải vào hàm ShoppingCart này và tạo View như các bài lab trước tôi đã hướng dẫn, sửa code của trang View ShoppingCart như sau:
?
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
@using VnExpress_NguyenDinhAnh.Models;
@{
    ViewBag.Title = "ShoppingCart";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<h2>Your Shopping Cart</h2>
 
<div class="table-responsive">
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>
                    Title
                </th>
                <th>
                    Author Name
                </th>
                <th>
                    Price
                </th>
                <th>
                    Year
                </th>
                <th>
                    Cover Page
                </th>
                <th>
                    Quality
                </th>
                <th>
                    Total
                </th>
            </tr>
        </thead>
        @{
            double total = 0;
            List<CartItem> listCart = (List<CartItem>)Session["ShoppingCart"];
        }
        <tbody>
            @if (listCart != null)
            {
                foreach (var item in (List<CartItem>)Session["ShoppingCart"])
                {
                    <tr>
                        <td>
                            @item.productOrder.Title
                        </td>
                        <td>
                            @item.productOrder.AuthorName
                        </td>
                        <td>
                            @item.productOrder.Price
                        </td>
                        <td>
                            @item.productOrder.Year
                        </td>
                        <td>
                            <img src="@item.productOrder.CoverPage" alt="cover page" width="80" />
                        </td>
                        <td>
                            <input type="text" value="@item.Quality" id="Quality" class="text-center" /> &nbsp;
                            <input type="submit" value="Update" class="btn btn-warning" id="Update" />
                        </td>
                        <td>
                            @{
                                double value = (double)item.productOrder.Price * item.Quality;
                                total += value;
                            }
                            @value
                        </td>
                    </tr>
 
                                }
                                }
        </tbody>
        <tfoot>
            <tr>
                <td colspan="7" class="text-right">
                    <strong>Total: @total</strong>
                </td>
            </tr>
        </tfoot>
    </table>
    <p class="pull-right">
        <input type="submit" class="btn btn-info" value="Continue shopping" /> &nbsp;
        <input type="submit" class="btn btn-danger" value="CheckOut" />
    </p>
</div>
Xong ứng dụng tạo giỏ hàng bằng kỹ thuật xử lý Ajax và dùng session để lưu trữ.

Không có nhận xét nào:

Đăng nhận xét