经过一段时间的准备,新的一期【ASP.NET Core MVC开发实战之商城系统】已经开始,在之前的文章中,讲解了商城系统的整体功能设计,页面布局设计,环境搭建,系统配置,及首页【商品类型,banner条,友情链接,降价促销,新品爆款】,商品列表页面,商品详情等功能的开发,今天继续讲解购物车功能开发,仅供学习分享使用,如有不足之处,还请指正。
在首页或者商品列表页面,如果用户对商品感兴趣,可以点击快捷方式,将商品加入购物车;或者在商品详情页面,选择对应的商品参数后,将商品加入购物车。商品加入购物车的渠道是有多种,而用户也可以对已经加入购物车的商品进行购买,或者删除购物车。每一个用户都有各自的购物车,相互之间独立,所以购物车功能需要用户先进行登录,才能查看。
根据购物车功能说明,购物车主要显示已添加的商品列表,并可以删除,或者选择商品进行购买,设计页面如下所示:
购物车主要展示用户选择的商品信息。
购物车表EB_Cart主要用于存储商品信息,用户信息,数量,及个人喜好等内容,如下所示:
购物车表创建语句如下所示:
CREATE TABLE [dbo].[EB_Cart](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[ProductId] [bigint] NULL,
[CustomerId] [bigint] NULL,
[Quantity] [int] NULL,
[Remark] [varchar](200) NULL,
[CreateTime] [datetime] NULL,
[CreateUser] [varchar](50) NULL,
[LastEditTime] [datetime] NULL,
[LastEditUser] [varchar](50) NULL
) ON [PRIMARY]
购物车实体和数据表结构保持一致,方便进行映射。如下所示:
using SqlSugar;
namespace EasyBuyShop.Models
{
///
/// 购物车
///
[SugarTable("EB_Cart")]
public class Cart:EntityModel
{
public long ProductId { get; set; }
public long CustomerId { get; set; }
///
/// 数量
///
public int Quantity { get; set; }
public string Remark { get; set; }
}
}
购物车列表,主要包括添加购物车,删除,查询等功能,DAL层代码如下所示:
using EasyBuyShop.Models;
using EasyBuyShop.Utils;
namespace EasyBuyShop.DAL
{
public class CartDal:BaseDal
{
///
/// 获取购物车列表
///
///
///
public List GetCartListByUserId(long userId)
{
try
{
using (var db = this.GetDb(BaseDal.ConnStr))
{
return db.Queryable().Where(r => r.CustomerId == userId).ToList();
}
}
catch (Exception ex)
{
LogHelper.Fatal(ex.Message);
return new List();
}
}
public int DeleteById(long id)
{
try
{
using (var db = this.GetDb(BaseDal.ConnStr))
{
int cnt = db.Deleteable(r => r.Id == id).ExecuteCommand();
return cnt;
}
}
catch (Exception ex)
{
LogHelper.Fatal(ex.Message);
return -1;
}
}
public Cart GetCart(long id)
{
try
{
using (var db = this.GetDb(BaseDal.ConnStr))
{
return db.Queryable().First(r => r.Id == id);
}
}
catch (Exception ex)
{
LogHelper.Fatal(ex.Message);
return null;
}
}
}
}
控制器方法主要包括添加购物车【1.首页或商品列表快捷添加购物车 2.商品详情页面添加购物车】,查询购物车, 删除购物车,代码如下所示:
using EasyBuyShop.DAL;
using EasyBuyShop.Models;
using Microsoft.AspNetCore.Mvc;
namespace EasyBuyShop.Controllers
{
///
/// 购物车控制器
///
public class CartController : Controller
{
///
/// 购物车列表页面
///
///
public IActionResult Index()
{
var userId = HttpContext.Session.GetInt32("userid");
if (userId == null)
{
return Redirect("/Auth/login");
}
var cartDal = new CartDal();
var productDal = new ProductDal();
var cartList = cartDal.GetCartListByUserId((long)userId);
var products = productDal.GetProductListByIds(cartList.Select(r => r.ProductId).ToList());
ViewData["CartList"] = cartList;
ViewData["ProductList"]= products;
var username = HttpContext.Session.GetString("username");
var realName = HttpContext.Session.GetString("realname");
ViewData["Username"] = username;
ViewData["RealName"] = realName;
return View();
}
///
/// 首页或商品列表,快捷加入购物车
///
///
///
[HttpPost]
public IActionResult Add(int productId)
{
Msg msg = new Msg();
var userId = HttpContext.Session.GetInt32("userid");
var userName= HttpContext.Session.GetString("username");
if (userId == null)
{
msg.code = -1;
msg.message = "尚未登录";
return Json(msg);
}
var productDal = new ProductDal();
var product = productDal.GetProduct(productId);
if (product != null)
{
var cartDal = new CartDal();
var cart=new Cart();
cart.ProductId = productId;
cart.CustomerId = userId.Value;
cart.Quantity = 1;
cart.Remark= string.Empty;
cart.CreateUser = userName;
cart.CreateTime=DateTime.Now;
cart.LastEditUser = userName;
cart.LastEditTime = DateTime.Now;
int id = cartDal.InsertT(cart);
if(id > 0)
{
msg.code = 0;
msg.message = "成功";
return Json(msg);
}
else
{
msg.code = -1;
msg.message = "加入购物车失败";
return Json(msg);
}
}
else
{
msg.code = -1;
msg.message = "商品不存在";
return Json(msg);
}
}
///
/// 商品详情页面加入购物车
///
///
[HttpPost]
public IActionResult AddWithForm()
{
Msg msg = new Msg();
var userId = HttpContext.Session.GetInt32("userid");
var userName = HttpContext.Session.GetString("username");
if (userId == null)
{
msg.code = -1;
msg.message = "尚未登录";
return Json(msg);
}
var productId =long.Parse( Request.Form["productId"]);
var quantity = int.Parse(Request.Form["quantity"]);
var color = Request.Form["color"];
var size = Request.Form["size"];
var remark = $"颜色:{color},大小:{size}";
var productDal = new ProductDal();
var product = productDal.GetProduct(productId);
if (product != null)
{
var cartDal = new CartDal();
var cart = new Cart();
cart.ProductId = productId;
cart.CustomerId = userId.Value;
cart.Quantity = quantity;
cart.Remark = remark;
cart.CreateUser = userName;
cart.CreateTime = DateTime.Now;
cart.LastEditUser = userName;
cart.LastEditTime = DateTime.Now;
int id = cartDal.InsertT(cart);
if (id > 0)
{
msg.code = 0;
msg.message = "成功";
}
else
{
msg.code = -1;
msg.message = "加入购物车失败";
}
}
else
{
msg.code = -1;
msg.message = "商品不存在";
}
return Redirect("/Cart/Index");
}
///
/// 移除购物车
///
///
///
public ActionResult Delete(int Id)
{
var cartDal =new CartDal();
if(cartDal.DeleteById(Id) > 0)
{
//成功
}
else
{
//删除失败
}
return View();
}
}
}
在Views/Cart/Index.cshtml购物车视图中,接收控制器传递的参数。如下所示:
@{
var totalPrice = 0.0M;
}
运行程序,点击登录,在登录成功后,在右上角个人名称,点击下拉菜单,选择购物车,然后打开购物车页面,如下所示:
以上就是ASP.NET Core MVC开发实战之商城系统第五部分内容,后续将继续介绍其他模块,敬请期待。