c#購物車功能實現,用戶登錄及收藏功能實現

来源:https://www.cnblogs.com/bwxw/archive/2020/07/26/13381989.html
-Advertisement-
Play Games

一.思路邏輯: 首先我先來說一下我自己的理解,一個萌新的見解,要實現購物車的功能,首先要獲取到登錄時的用戶id及商品的編號(商品id),這裡我用的模式是mvc模式進行實現功能的,用戶登錄時,利用session保存用戶的登錄用戶名,然後在控制器里進行傳值操作,定義一個session進行接收用戶輸入的用 ...


一.思路邏輯:

首先我先來說一下我自己的理解,一個萌新的見解,要實現購物車的功能,首先要獲取到登錄時的用戶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)
	   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 本系列將和大家分享面向對象23種設計模式中常用的幾種設計模式,本章主要簡單介紹下行為型設計模式。 ...
  • 都0202年了,不會還有人在用WPF吧,不會吧不會吧~什麼qt啊,electron啊,flutter啊好多東西要學啊,我還是繼續用WPF吧。因為其它的還不太會;繼續學習吧~ 期待WinUI3和“MAUI”-2021 1.周末沒加班,閑來沒事做;模仿個東西好了;在模仿中學習(各位大佬不要嘲諷我就是~) ...
  • 首次發表,不太會寫,那點乾貨上個分,廢話不多說,不懂多看 1 public void Publist() 2 { 3 ResultListData resultData = new ResultListData(); 4 BLL.basic_project bllspro = new BLL.bas ...
  • .net core 和.net framework上傳文件還是有一些區別的有很多註意的地方 .net framework 上傳文件用httppostedfilebase .net core 上傳文件用 IFormFile 下麵廢話不多說了,直接上代碼 控制器裡面寫 using System; usi ...
  • 一、簡介 ABP vNext 在 v 2.9.x 版本當中添加了 BLOB 系統,主要用於存儲大型二進位文件。ABP 抽象了一套通用的 BLOB 體系,開發人員在存儲或讀取二進位文件時,可以忽略具體實現,直接使用 IBlobContainer 或 IBlobContainer<T> 進行操作。官方的 ...
  • 使用 .NET Core WebAPI 實現一個 VPS 下載中轉(加速)器 VPSDownloader.NET,暨 .NET Core 程式部署到 Linux 系統。 ...
  • 最近想給我的框架加一種功能,就是比如給一個方法加一個事務的特性Attribute,那這個方法就會啟用事務處理。給一個方法加一個緩存特性,那這個方法就會進行緩存。 這個也是網上說的面向切麵編程AOP。 AOP的概念也很好理解,跟中間件差不多,說白了,就是我可以任意地在方法的前面或後面添加代碼,這很適合 ...
  • Tips:本篇已加入系列文章閱讀目錄,可點擊查看更多相關文章。 前言 上一篇【.Net Core in Docker極簡入門(上篇)】講解了docker的一些基本命令和操作,併成功構建了自己的asp.net core web應用的鏡像,啟動容器。本篇繼續。 開始 上一篇的項目例子非常簡單,通常我們的 ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...