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
  • 概述:在C#中,++i和i++都是自增運算符,其中++i先增加值再返回,而i++先返回值再增加。應用場景根據需求選擇,首碼適合先增後用,尾碼適合先用後增。詳細示例提供清晰的代碼演示這兩者的操作時機和實際應用。 在C#中,++i 和 i++ 都是自增運算符,但它們在操作上有細微的差異,主要體現在操作的 ...
  • 上次發佈了:Taurus.MVC 性能壓力測試(ap 壓測 和 linux 下wrk 壓測):.NET Core 版本,今天計劃準備壓測一下 .NET 版本,來測試並記錄一下 Taurus.MVC 框架在 .NET 版本的性能,以便後續持續優化改進。 為了方便對比,本文章的電腦環境和測試思路,儘量和... ...
  • .NET WebAPI作為一種構建RESTful服務的強大工具,為開發者提供了便捷的方式來定義、處理HTTP請求並返迴響應。在設計API介面時,正確地接收和解析客戶端發送的數據至關重要。.NET WebAPI提供了一系列特性,如[FromRoute]、[FromQuery]和[FromBody],用 ...
  • 原因:我之所以想做這個項目,是因為在之前查找關於C#/WPF相關資料時,我發現講解圖像濾鏡的資源非常稀缺。此外,我註意到許多現有的開源庫主要基於CPU進行圖像渲染。這種方式在處理大量圖像時,會導致CPU的渲染負擔過重。因此,我將在下文中介紹如何通過GPU渲染來有效實現圖像的各種濾鏡效果。 生成的效果 ...
  • 引言 上一章我們介紹了在xUnit單元測試中用xUnit.DependencyInject來使用依賴註入,上一章我們的Sample.Repository倉儲層有一個批量註入的介面沒有做單元測試,今天用這個示例來演示一下如何用Bogus創建模擬數據 ,和 EFCore 的種子數據生成 Bogus 的優 ...
  • 一、前言 在自己的項目中,涉及到實時心率曲線的繪製,項目上的曲線繪製,一般很難找到能直接用的第三方庫,而且有些還是定製化的功能,所以還是自己繪製比較方便。很多人一聽到自己畫就害怕,感覺很難,今天就分享一個完整的實時心率數據繪製心率曲線圖的例子;之前的博客也分享給DrawingVisual繪製曲線的方 ...
  • 如果你在自定義的 Main 方法中直接使用 App 類並啟動應用程式,但發現 App.xaml 中定義的資源沒有被正確載入,那麼問題可能在於如何正確配置 App.xaml 與你的 App 類的交互。 確保 App.xaml 文件中的 x:Class 屬性正確指向你的 App 類。這樣,當你創建 Ap ...
  • 一:背景 1. 講故事 上個月有個朋友在微信上找到我,說他們的軟體在客戶那邊隔幾天就要崩潰一次,一直都沒有找到原因,讓我幫忙看下怎麼回事,確實工控類的軟體環境複雜難搞,朋友手上有一個崩潰的dump,剛好丟給我來分析一下。 二:WinDbg分析 1. 程式為什麼會崩潰 windbg 有一個厲害之處在於 ...
  • 前言 .NET生態中有許多依賴註入容器。在大多數情況下,微軟提供的內置容器在易用性和性能方面都非常優秀。外加ASP.NET Core預設使用內置容器,使用很方便。 但是筆者在使用中一直有一個頭疼的問題:服務工廠無法提供請求的服務類型相關的信息。這在一般情況下並沒有影響,但是內置容器支持註冊開放泛型服 ...
  • 一、前言 在項目開發過程中,DataGrid是經常使用到的一個數據展示控制項,而通常表格的最後一列是作為操作列存在,比如會有編輯、刪除等功能按鈕。但WPF的原始DataGrid中,預設只支持固定左側列,這跟大家習慣性操作列放最後不符,今天就來介紹一種簡單的方式實現固定右側列。(這裡的實現方式參考的大佬 ...