VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • c#购物车功能实现,用户登录及收藏功能实现

一.思路逻辑:

首先我先来说一下我自己的理解,一个萌新的见解,要实现购物车的功能,首先要获取到登录时的用户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 }
复制代码
复制代码
 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 }
复制代码
复制代码
 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 }
复制代码
复制代码
 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 }
复制代码

搭建好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 }
复制代码
复制代码
 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 }
复制代码
复制代码
 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 }
复制代码
复制代码
 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 }
复制代码

 

控制器里的方法(因为这里我是搭三层写的,有个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 }
复制代码

登录视图中的代码如下:

复制代码
 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>
复制代码

商品显示的视图代码如下:

复制代码
 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();" />&nbsp;<input value="收藏" type="button" onclick="MyFavorite();" />&nbsp;<input value="加入购物车" type="button" onclick="MyShoppingCar();" />&nbsp;<input value="我的购物车" type="button" onclick="ToMyShoppingCar();" />
93 <table id="tbProduct"></table>
复制代码

购物车显示的视图代码如下:

复制代码
  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 + '" />&nbsp;';
 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)" />全选&nbsp;商品
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()"/>
复制代码

文章出处:https://www.cnblogs.com/bwxw/p/13381989.html



相关教程