一.思路逻辑:
首先我先来说一下我自己的理解,一个萌新的见解,要实现购物车的功能,首先要获取到登录时的用户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 MODEL10 {11 //购物车表12 [Table("MyShoppingCar")]13 public class MyShoppingCar14 {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 MODEL10 {11 //收藏表12 [Table("MyFavorite")]13 public class MyFavorite14 {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 Product11 {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 MODEL10 {11 //登录用户表12 [Table("UserInfo")]13 public class UserInfo14 {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 MyFavoriteDAL10 {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 MyShoppingCarDAL11 {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 ListGetList(string userid)30 {31 using (Model1 mc = new Model1())32 {33 34 var query = from s in mc.Products35 from t in mc.MyShoppingCars36 where s.Pno == t.Pno && t.UserId== userid37 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 //加减155 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 else63 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 ProductDAL11 {12 //商品显示的方法13 public ListGetList(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 UserInfoDAL10 {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.Controllers10 {11 public class HomeController : Controller12 {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 //获取产品的List57 [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 //获取我的购物车列表信息List66 [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 //加减182 [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 Login 6 <script src="~/Scripts/jquery-3.3.1.min.js"> 7 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 " _ue_custom_node_="true">42 <table border="1">43 44 账号:45 <input type="text" id="txtAmount" />46 47 48 密码:49 <input type="password" id="txtPwd" />50 51 52 <td colspan="2">53 <input value="登录" type="button" id="btnLogin" onclick="LoginCheck()" />54 55 56
Login.cshtml
商品显示的视图代码如下:
1 @{ 2 ViewBag.Title = "Home Page"; 3 Layout = null; 4 } 5 <script src="~/Scripts/jquery-3.3.1.min.js"> 6 7 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 ) {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 ) {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 ) {72 var tr = ' ';73 tr += ' ';74 tr += '' + data[i].ImgPath + '" />';75 tr += '';76 tr += data[i].Price;77 tr += '';78 tr += data[i].Pname;79 tr += '';80 tr += '' + data[i].Pno + '" />';81 tr += ' ';82 83 tr += "";84 $("#tbProduct").append(tr);85 }86 }87 })88 }89 90 " _ue_custom_node_="true">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">
Index.cshtml
购物车显示的视图代码如下:
1 @{ 2 ViewBag.Title = "MyShoppingCar"; 3 // Layout = null; 4 } 5 6 我的购物车 7 <script src="~/Scripts/jquery-3.3.1.min.js"> 8 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 ) { 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 ) { 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 ) { 89 var tr = ' '; 90 91 //商品 92 tr += ' '; 93 tr += '' + data[i].Id + '" /> '; 94 tr += '' + data[i].ImgPath + '" />'; 95 tr += ''; 96 tr += data[i].Pname; 97 tr += ' '; 98 99 //单价100 tr += ' ';101 tr += data[i].Price;102 tr += ' ';103 104 //数量105 tr += ' ';106 tr += '' + data[i].Id + ',\'down\')">-' + data[i].Account + '" style="width:20px" />' + data[i].Id + ',\'up\')">+';107 tr += ' ';108 109 //小计110 tr += ' ';111 tr += data[i].TotalMoney;112 tr += ' ';113 114 //操作115 tr += ' ';116 tr += '' + data[i].Id+')" />';117 tr += ' ';118 119 tr += "";120 $("#tbProduct").append(tr);121 }122 }123 })124 }125 126 " _ue_custom_node_="true">127 <table border="1" width="100%">128 129 130 131 <input type="checkbox" onclick="CheckAll(this)" />全选 商品132 133 134 单价135 136 137 数量138 139 140 小计141 142 143 操作144 145 146 147 <tbody id="tbProduct">148 149 150 151 <input type="button" value="批量删除" onclick="BathDel()"/>
View Code