经过一段时间的准备,新的一期【ASP.NET Core MVC开发实战之商城系统】已经开始,在之前的文章中,讲解了商城系统的整体功能设计,页面布局设计,环境搭建,系统配置,及首页【商品类型,banner条,友情链接,降价促销,新品爆款】,商品列表页面,商品详情等功能的开发,今天继续讲解购物车功能开发,仅供学习分享使用,如有不足之处,还请指正。
购物车功能说明
在首页或者商品列表页面,如果用户对商品感兴趣,可以点击快捷方式,将商品加入购物车;或者在商品详情页面,选择对应的商品参数后,将商品加入购物车。商品加入购物车的渠道是有多种,而用户也可以对已经加入购物车的商品进行购买,或者删除购物车。每一个用户都有各自的购物车,相互之间独立,所以购物车功能需要用户先进行登录,才能查看。
购物车功能设计
根据购物车功能说明,购物车主要显示已添加的商品列表,并可以删除,或者选择商品进行购买,设计页面如下所示:
购物车功能开发
购物车主要展示用户选择的商品信息。
1. 数据表创建
购物车表EB_Cart主要用于存储商品信息,用户信息,数量,及个人喜好等内容,如下所示:
购物车表创建语句如下所示:
sql
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]
2. 购物车实体创建
购物车实体和数据表结构保持一致,方便进行映射。如下所示:
cs
using SqlSugar;
namespace EasyBuyShop.Models
{
/// <summary>
/// 购物车
/// </summary>
[SugarTable("EB_Cart")]
public class Cart:EntityModel
{
public long ProductId { get; set; }
public long CustomerId { get; set; }
/// <summary>
/// 数量
/// </summary>
public int Quantity { get; set; }
public string Remark { get; set; }
}
}
3. 数据处理层DAL
购物车列表,主要包括添加购物车,删除,查询等功能,DAL层代码如下所示:
cs
using EasyBuyShop.Models;
using EasyBuyShop.Utils;
namespace EasyBuyShop.DAL
{
public class CartDal:BaseDal
{
/// <summary>
/// 获取购物车列表
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public List<Cart> GetCartListByUserId(long userId)
{
try
{
using (var db = this.GetDb(BaseDal.ConnStr))
{
return db.Queryable<Cart>().Where(r => r.CustomerId == userId).ToList();
}
}
catch (Exception ex)
{
LogHelper.Fatal(ex.Message);
return new List<Cart>();
}
}
public int DeleteById(long id)
{
try
{
using (var db = this.GetDb(BaseDal.ConnStr))
{
int cnt = db.Deleteable<Cart>(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<Cart>().First(r => r.Id == id);
}
}
catch (Exception ex)
{
LogHelper.Fatal(ex.Message);
return null;
}
}
}
}
4. 控制器获取
控制器方法主要包括添加购物车【1.首页或商品列表快捷添加购物车 2.商品详情页面添加购物车】,查询购物车, 删除购物车,代码如下所示:
cs
using EasyBuyShop.DAL;
using EasyBuyShop.Models;
using Microsoft.AspNetCore.Mvc;
namespace EasyBuyShop.Controllers
{
/// <summary>
/// 购物车控制器
/// </summary>
public class CartController : Controller
{
/// <summary>
/// 购物车列表页面
/// </summary>
/// <returns></returns>
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();
}
/// <summary>
/// 首页或商品列表,快捷加入购物车
/// </summary>
/// <param name="productId"></param>
/// <returns></returns>
[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>(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);
}
}
/// <summary>
/// 商品详情页面加入购物车
/// </summary>
/// <returns></returns>
[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>(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");
}
/// <summary>
/// 移除购物车
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public ActionResult Delete(int Id)
{
var cartDal =new CartDal();
if(cartDal.DeleteById(Id) > 0)
{
//成功
}
else
{
//删除失败
}
return View();
}
}
}
5. 视图层展示
在Views/Cart/Index.cshtml购物车视图中,接收控制器传递的参数。如下所示:
html
@{
var totalPrice = 0.0M;
}
<div class="content-wrap">
<div class="content">
<!-- shopping-cart-area start -->
<div class="cart-area ptb-100">
<form action="/Purchase/BuyWithCart" method="post">
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="table-content table-responsive">
<table>
<thead>
<tr>
<th class="product-check">选择</th>
<th class="product-price">图片</th>
<th class="product-name">产品名称</th>
<th class="product-price">价格</th>
<th class="product-price">优惠价格</th>
<th class="product-quantity">数量</th>
<th class="product-subtotal">总计</th>
<th class="product-name">删除</th>
</tr>
</thead>
<tbody>
@{
var cartList = ViewData["CartList"] as List<Cart>;
var productList = ViewData["ProductList"] as List<Product>;
if (cartList.Count > 0)
{
foreach (var cart in cartList)
{
var product = productList.FirstOrDefault(r => r.Id == cart.ProductId);
totalPrice = totalPrice + (product.PreferentialPrice * cart.Quantity);
<tr>
<td class="product-check">
<input type="checkbox" value="@(cart.Id)" name="chkCart" style="width:25px;height:25px;" checked="checked" onchange="javascript:checkCartProduct(this);" />
</td>
<td class="product-thumbnail">
<a href="/Product/Detail/@(product.Id)"><img src="@(product.ImageUrl)" alt="" width="100" height="100"></a>
</td>
<td class="product-name">
<a href="/Product/Detail/@(product.Id)">@product.Name</a>
<br />
<span style="font-size:12px; color:lightgray">备注:@(string.IsNullOrEmpty(cart.Remark) ? "无" : cart.Remark)</span>
</td>
<td class="product-price"><span class="amount">@(Math.Round(product.Price, 2))</span></td>
<td class="product-price"><span class="amount">@(Math.Round(product.PreferentialPrice, 2))</span></td>
<td class="product-quantity">
<input value="@(cart.Quantity)" type="number">
</td>
<td class="product-subtotal">@(Math.Round(product.PreferentialPrice * cart.Quantity, 2))</td>
<td class="product-remove">
<a href="/Cart/Delete/@(cart.Id)">
<i class="fa fa-times"><font style="font-size:14px;">删除</font></i>
</a>
</td>
</tr>
}
}
else
{
<tr><td colspan="7">购物车暂无商品</td></tr>
}
}
</tbody>
</table>
</div>
</div>
</div>
<div class="row tax-coupon-div">
<div class="col-md-7 col-sm-12 col-xs-12">
</div>
<div class="col-md-5 col-sm-12 col-xs-12">
<div class="cart-total">
<ul>
<li class="cart-black">总计<span>@totalPrice</span></li>
</ul>
<div class="cart-total-btn">
<div class="cart-total-btn1 f-left">
</div>
<div class="cart-total-btn2 f-right">
<input type="submit" value="购买" class="go-btn" onclick="javascript:return checkSubmit();" style="background-color: rgb(255, 80, 0);border-width:0px;margin-top:5px;" />
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<!-- shopping-cart-area end -->
</div>
<!-- content end -->
</div>
<!-- content-wrap end -->
<script src="~/js/shop.js"></script>
购物车页面展示
运行程序,点击登录,在登录成功后,在右上角个人名称,点击下拉菜单,选择购物车,然后打开购物车页面,如下所示:
以上就是ASP.NET Core MVC开发实战之商城系统第五部分内容,后续将继续介绍其他模块,敬请期待。