一.思路邏輯:
首先我先來說一下我自己的了解,一個萌新的見解,要實作購物車的功能,首先要擷取到登入時的使用者id及商品的編号(商品id),這裡我用的模式是mvc模式進行實作功能的,使用者登入時,利用session儲存使用者的登入使用者名,然後在控制器裡進行傳值操作,定義一個session進行接收使用者輸入的使用者名,登入成功後進行儲存使用者的使用者名,登入成功,前台在進行跳轉到顯示界面,點選事先建立好的購物車按鈕,把我們已經儲存好的使用者名傳過去,在進行session接收使用者名字,添加到購物車時,前面我也說到需要兩個值,我們現在已經擷取到了使用者id(使用者名),再擷取到商品id就可以進行添加到購物車功能的實作,在顯示的ajax拼接字元串進行顯示的時候,我們需要再添加一個多選按鈕(多選按鈕是為了進行多項資料選擇時,添加到購物車以及添加收藏時更友善一些),為多選按鈕添加一個id屬性或者name屬性,這裡是為了我們友善擷取它的資料,擷取多選框的id值的方法我就不在這裡過多介紹了,既然我們需要的兩個值都已經擷取到,我們的添加購物車功能就可以實作了大佬們看過之後,若是有空閑時間,在評論區多給國小生一些建議,我會進行改正的.
二.代碼如下:
執行個體化模型層(model層),共建立了四個表,我用的方法是EF架構中的codefirst方法,詳細解釋大家可以百度,或者可以看一看另一個部落客的部落格,https://www.cnblogs.com/zpyplan/p/9565863.html:

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using System.ComponentModel.DataAnnotations;
7 using System.ComponentModel.DataAnnotations.Schema;
8
9 namespace MODEL
10 {
11 //購物車表
12 [Table("MyShoppingCar")]
13 public class MyShoppingCar
14 {
15 [Key]
16 public int Id { get; set; }
17 public string UserId { get; set; }
18 public string Pno { get; set; }
19 public int? Account { get; set; }
20 }
21 }
MyShoppingCar

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using System.ComponentModel.DataAnnotations;
7 using System.ComponentModel.DataAnnotations.Schema;
8
9 namespace MODEL
10 {
11 //收藏表
12 [Table("MyFavorite")]
13 public class MyFavorite
14 {
15 [Key]
16 public string UserId { get; set; }
17 public string Pno { get; set; }
18 }
19 }
MyFavorite

1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel.DataAnnotations;
4 using System.ComponentModel.DataAnnotations.Schema;
5
6 namespace MODEL
7 {
8 //商品表
9 [Table("Product")]
10 public class Product
11 {
12 [Key]
13 public int Id { get; set; }
14 public string Pno { get; set; }
15 public string Pname { get; set; }
16 public int? Price { get; set; }
17 public string ImgPath { get; set; }
18 }
19 }
Product

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using System.ComponentModel.DataAnnotations;
7 using System.ComponentModel.DataAnnotations.Schema;
8
9 namespace MODEL
10 {
11 //登入使用者表
12 [Table("UserInfo")]
13 public class UserInfo
14 {
15 [Key]
16 public String UserID { get; set; }
17 public String UserName { get; set; }
18 public String WX { get; set; }
19 public String Pwd { get; set; }
20 public String QQ { get; set; }
21 }
22 }
UserInfo
搭建好model層,我們要開始寫dal層裡的方法了,我們要實作的功能有使用者登入功能,商品的顯示功能,添加到購物車功能,加減一功能,收藏功能,顯示購物車清單,批量删除購物車
dal層如下(codefirst方法):

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace DAL
8 {
9 public class MyFavoriteDAL
10 {
11 public int Favorite(string userid,string pnos)
12 {
13 string[] arr = pnos.Trim(',').Split(',');
14 using (Model1 mc = new Model1())
15 {
16 foreach (string str in arr)
17 {
18 string sql = $"insert into MyFavorite(userid,pno) values('{userid}','{str}')";
19 mc.Database.ExecuteSqlCommand(sql);
20 }
21 }
22
23 return 1;
24 }
25 }
26 }
MyFavoriteDAL

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using MODEL;
7
8 namespace DAL
9 {
10 public class MyShoppingCarDAL
11 {
12 //添加到購物車的方法
13 public int AddMyShoppingCar(string userid, string pnos)
14 {
15 string[] arr = pnos.Trim(',').Split(',');
16 using (Model1 mc = new Model1())
17 {
18 foreach (string str in arr)
19 {
20 string sql = $"insert into MyShoppingCar(userid,pno,Account) values('{userid}','{str}',1)";
21 mc.Database.ExecuteSqlCommand(sql);
22 }
23 }
24
25 return 1;
26 }
27
28 //擷取購物車的資訊
29 public List<V_MyShoppingCar> GetList(string userid)
30 {
31 using (Model1 mc = new Model1())
32 {
33
34 var query = from s in mc.Products
35 from t in mc.MyShoppingCars
36 where s.Pno == t.Pno && t.UserId== userid
37 select new V_MyShoppingCar { Pno = s.Pno, Pname = s.Pname, Price = s.Price, Id = t.Id, Account = t.Account, TotalMoney = t.Account * s.Price, ImgPath=s.ImgPath };
38 return query.ToList();
39 }
40 }
41
42 //批量删除
43 public int DelMyShoppingCars(string ids)
44 {
45 //1,2,3,4,....
46 using (Model1 mc = new Model1())
47 {
48 string sql = $"delete MyShoppingCar where id in({ids.Trim(',')})";
49 mc.Database.ExecuteSqlCommand(sql);
50 }
51 return 1;
52 }
53
54 //加減1
55 public int MyShoppingCarsUpDown(string id,string sType)
56 {
57 using (Model1 mc = new Model1())
58 {
59 string sql;
60 if (sType.Equals("up"))
61 sql = $"update MyShoppingCar set Account=Account+1 where id={id}";
62 else
63 sql = $"update MyShoppingCar set Account=Account-1 where id={id}";
64 mc.Database.ExecuteSqlCommand(sql);
65 }
66 return 1;
67 }
68
69 }
70 }
MyShoppingCarDAL

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using MODEL;
7
8 namespace DAL
9 {
10 public class ProductDAL
11 {
12 //商品顯示的方法
13 public List<Product> GetList(string pname)
14 {
15 using (Model1 mc = new Model1())
16 {
17 //linq查詢
18 return mc.Products.Where(x=>x.Pname.Contains(pname)).ToList();
19 }
20 }
21
22
23
24 }
25 }
ProductDAL

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace DAL
8 {
9 public class UserInfoDAL
10 {
11 //使用者登良路的方法
12 public int Login(string userid,string pwd)
13 {
14 using (Model1 mc = new Model1())
15 {
16 //linq查詢的方法
17 return mc.UserInfos.Where(x => x.UserID.Equals(userid) && x.Pwd.Equals(pwd)).Count();
18 }
19 }
20 }
21 }
UserInfoDAL
控制器裡的方法(因為這裡我是搭三層寫的,有個bll層,也就是業務邏輯層,控制器裡調用的方法大多是調用的業務邏輯層的方法,因為我吧所有業務處理的代碼都寫在了dal層,我在這裡就不寫bll層了,複制代碼時隻需将bll層的方法調用替換成dal層的方法調用):

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.Mvc;
6 using BLL;
7 using MODEL;
8
9 namespace WT01.Controllers
10 {
11 public class HomeController : Controller
12 {
13 UserInfoBLL bll = new UserInfoBLL();
14
15 //登入頁面
16 public ActionResult Login()
17 {
18 return View();
19 }
20 //顯示頁面
21 public ActionResult Index()
22 {
23 return View();
24 }
25 //購物車頁面
26 public ActionResult MyShoppingCar()
27 {
28 return View();
29 }
30
31 //登入驗證
32 [HttpPost]
33 public int LoginValidate(string userid,string pwd)
34 {
35 HttpContext.Session["userid"] = userid;
36 return bll.Login(userid, pwd);
37 }
38
39 //收藏
40 [HttpPost]
41 public int Favorite(string pnos)
42 {
43 string userid= HttpContext.Session["userid"].ToString();
44 return new MyFavoriteBLL().Favorite(userid, pnos);
45 }
46
47 //加入購物車
48 [HttpPost]
49 public int AddMyShoppingCar(string pnos)
50 {
51 string userid = HttpContext.Session["userid"].ToString();
52 return new MyShoppingCarBLL().AddMyShoppingCar(userid, pnos);
53 }
54
55
56 //擷取産品的List
57 [HttpGet]
58 public JsonResult GetList(string pname)
59 {
60 ProductBLL productBLL = new ProductBLL();
61 return Json(productBLL.GetList(pname),JsonRequestBehavior.AllowGet);
62 }
63
64
65 //擷取我的購物車清單資訊List
66 [HttpGet]
67 public JsonResult GetMyShoppingCarList()
68 {
69 MyShoppingCarBLL myShoppingCar = new MyShoppingCarBLL();
70 string userid = HttpContext.Session["userid"].ToString();
71 return Json(myShoppingCar.GetList(userid), JsonRequestBehavior.AllowGet);
72 }
73
74 //批量删除購物車
75 [HttpPost]
76 public int DelMyShoppingCar(string ids)
77 {
78 return new MyShoppingCarBLL().DelMyShoppingCars(ids);
79 }
80
81 //加減1
82 [HttpPost]
83 public int MyShoppingCarsUpDown(string id, string sType)
84 {
85 return new MyShoppingCarBLL().MyShoppingCarsUpDown(id, sType);
86 }
87
88 }
89 }
HomeController
登入視圖中的代碼如下:

1 @{
2 ViewBag.Title = "Login";
3
4 }
5 <h2>Login</h2>
6 <script src="~/Scripts/jquery-3.3.1.min.js"></script>
7 <script>
8
9 //驗證登入
10 function LoginCheck() {
11 var userid = $("#txtAmount").val();
12 var pwd = $("#txtPwd").val();
13
14 if (userid == "") {
15 alert("賬号不能為空!");
16 return;
17 }
18 if (pwd == "") {
19 alert("賬号不能為空!");
20 return;
21 }
22
23
24 $.ajax({
25 url: '/Home/LoginValidate',
26 type: 'post',
27 dataType: 'json',
28 data: { userid: userid, pwd: pwd },
29 success: function (data) {
30 if (data > 0) {
31 location.href = '/Home/Index';
32 }
33 else {
34 alert("賬号或密碼錯誤,請重新輸入");
35 location.href = '/Home/Login';
36 }
37 }
38 })
39 }
40
41 </script>
42 <table border="1">
43 <tr>
44 <td>賬号:</td>
45 <td><input type="text" id="txtAmount" /></td>
46 </tr>
47 <tr>
48 <td>密碼:</td>
49 <td><input type="password" id="txtPwd" /></td>
50 </tr>
51 <tr>
52 <td colspan="2">
53 <input value="登入" type="button" id="btnLogin" onclick="LoginCheck()" />
54 </td>
55 </tr>
56 </table>
Login.cshtml
商品顯示的視圖代碼如下:

1 @{
2 ViewBag.Title = "Home Page";
3 Layout = null;
4 }
5 <script src="~/Scripts/jquery-3.3.1.min.js"></script>
6
7 <script>
8
9 //文檔就緒函數
10 $(function () {
11 QueryList();
12 })
13
14 //收藏
15 function MyFavorite() {
16 var arr = document.getElementsByName("xselect");
17 var str = "";
18 for (var i = 0; i < arr.length; i++) {
19 if (arr[i].checked)
20 str += arr[i].id + ",";
21 }
22 //alert(str);
23 $.ajax({
24 url: '/Home/Favorite',
25 type: 'post',
26 dataType: 'json',
27 data: { pnos: str },
28 success: function (data) {
29 if (data > 0)
30 alert("收藏成功!");
31 }
32 })
33 }
34
35 //加入購物車
36 function MyShoppingCar() {
37 var arr = document.getElementsByName("xselect");
38 var str = "";
39 for (var i = 0; i < arr.length; i++) {
40 if (arr[i].checked)
41 str += arr[i].id + ",";
42 }
43 //alert(str);
44 $.ajax({
45 url: '/Home/AddMyShoppingCar',
46 type: 'post',
47 dataType: 'json',
48 data: { pnos: str },
49 success: function (data) {
50 if (data > 0)
51 alert("加入購物車成功!");
52 }
53 })
54 }
55
56 //轉到我的購物車
57 function ToMyShoppingCar() {
58 location.href ='/Home/MyShoppingCar'
59 }
60 //查詢資訊
61 function QueryList() {
62 var content = $("#txtContent").val();
63
64 $.ajax({
65 url: '/Home/GetList',
66 type: 'get',
67 dataType: 'json',
68 data: { pname: content },
69 success: function (data) {
70 $("#tbProduct").empty();
71 for (var i = 0; i < data.length; i++) {
72 var tr = ' <tr>';
73 tr += ' <td>';
74 tr += '<img src="../' + data[i].ImgPath + '" />';
75 tr += '<br>';
76 tr += data[i].Price;
77 tr += '<br>';
78 tr += data[i].Pname;
79 tr += '<br>';
80 tr += '<input name="xselect" type="checkbox" id="' + data[i].Pno + '" />';
81 tr += ' </td>';
82
83 tr += "</tr>";
84 $("#tbProduct").append(tr);
85 }
86 }
87 })
88 }
89
90 </script>
91
92 <input type="text" id="txtContent" /><input value="查詢" type="button" onclick="QueryList();" /> <input value="收藏" type="button" onclick="MyFavorite();" /> <input value="加入購物車" type="button" onclick="MyShoppingCar();" /> <input value="我的購物車" type="button" onclick="ToMyShoppingCar();" />
93 <table id="tbProduct"></table>
Index.cshtml
購物車顯示的視圖代碼如下:

1 @{
2 ViewBag.Title = "MyShoppingCar";
3 // Layout = null;
4 }
5
6 <h2>我的購物車</h2>
7 <script src="~/Scripts/jquery-3.3.1.min.js"></script>
8 <script>
9
10 //文檔就緒函數
11 $(function () {
12 QueryList();
13 })
14
15 //全選
16 function CheckAll(o) {
17 var chks = document.getElementsByName("xselect");
18 for (var i = 0; i < chks.length; i++) {
19 chks[i].checked = o.checked;
20 }
21 }
22
23 //批量删除
24 function BathDel() {
25 var chks = document.getElementsByName("xselect");
26 var ids = "";
27 for (var i = 0; i < chks.length; i++) {
28 if (chks[i].checked)
29 ids+= chks[i].id+",";
30 }
31 $.ajax({
32 url: '/Home/DelMyShoppingCar',
33 type: 'post',
34 dataType: 'json',
35 data: { ids: ids },
36 success: function (data) {
37 if (data > 0) {
38 QueryList();
39 alert('删除成功!');
40 }
41 }
42 })
43 }
44
45 //删除
46 function DelBid(id) {
47 $.ajax({
48 url: '/Home/DelMyShoppingCar',
49 type: 'post',
50 dataType: 'json',
51 data: { ids: id },
52 success: function (data) {
53 if (data > 0) {
54 QueryList();
55 alert('删除成功!');
56 }
57 }
58 })
59
60 }
61
62 //加減1
63 function upDown(id, sType) {
64 $.ajax({
65 url: '/Home/MyShoppingCarsUpDown',
66 type: 'post',
67 dataType: 'json',
68 data: { id: id, sType: sType},
69 success: function (data) {
70 if (data > 0) {
71 QueryList();
72 }
73 }
74 })
75
76 }
77
78 //查詢資訊
79 function QueryList() {
80
81 $.ajax({
82 url: '/Home/GetMyShoppingCarList',
83 type: 'get',
84 dataType: 'json',
85 success: function (data) {
86 $("#tbProduct").empty();
87 //拼接字元串
88 for (var i = 0; i < data.length; i++) {
89 var tr = ' <tr>';
90
91 //商品
92 tr += ' <td>';
93 tr += '<input name="xselect" type="checkbox" id="' + data[i].Id + '" /> ';
94 tr += '<img src="../' + data[i].ImgPath + '" />';
95 tr += '<br>';
96 tr += data[i].Pname;
97 tr += ' </td>';
98
99 //單價
100 tr += ' <td>';
101 tr += data[i].Price;
102 tr += ' </td>';
103
104 //數量
105 tr += ' <td>';
106 tr += '<a href="javascript:upDown(' + data[i].Id + ',\'down\')">-</a><input type="text" value="' + data[i].Account + '" style="width:20px" /><a href="javascript:upDown(' + data[i].Id + ',\'up\')">+</a>';
107 tr += ' </td>';
108
109 //小計
110 tr += ' <td>';
111 tr += data[i].TotalMoney;
112 tr += ' </td>';
113
114 //操作
115 tr += ' <td>';
116 tr += '<input type="button" value="删除" onclick="DelBid(' + data[i].Id+')" />';
117 tr += ' </td>';
118
119 tr += "</tr>";
120 $("#tbProduct").append(tr);
121 }
122 }
123 })
124 }
125
126 </script>
127 <table border="1" width="100%">
128 <thead>
129 <tr>
130 <th>
131 <input type="checkbox" onclick="CheckAll(this)" />全選 商品
132 </th>
133 <th>
134 單價
135 </th>
136 <th>
137 數量
138 </th>
139 <th>
140 小計
141 </th>
142 <th>
143 操作
144 </th>
145 </tr>
146 </thead>
147 <tbody id="tbProduct">
148
149 </tbody>
150 </table>
151 <input type="button" value="批量删除" onclick="BathDel()"/>
View Code
越是無知的人越是覺得自己無所不知(之前的自己)
越是學習的人越是覺得自己會的太少了(現在的自己)
共勉