[回馈]ASP.NET Core MVC开发实战之商城系统(五)
经过一段时间的准备,新的一期【ASP.NET Core MVC开发实战之商城系统】已经开始,在之前的文章中,讲解了商城系统的整体功能设计,页面布局设计,环境搭建,系统配置,及首页【商品类型,banner条,友情链接,降价促销,新品爆款】,商品列表页面,商品详情等功能的开发,今天继续讲解购物车功能开发,仅供学习分享使用,如有不足之处,还请指正。购物车功能说明
在首页或者商品列表页面,如果用户对商品感兴趣,可以点击快捷方式,将商品加入购物车;或者在商品详情页面,选择对应的商品参数后,将商品加入购物车。商品加入购物车的渠道是有多种,而用户也可以对已经加入购物车的商品进行购买,或者删除购物车。每一个用户都有各自的购物车,相互之间独立,所以购物车功能需要用户先进行登录,才能查看。
购物车功能设计
根据购物车功能说明,购物车主要显示已添加的商品列表,并可以删除,或者选择商品进行购买,设计页面如下所示:
购物车功能开发
购物车主要展示用户选择的商品信息。
1. 数据表创建
购物车表EB_Cart主要用于存储商品信息,用户信息,数量,及个人喜好等内容,如下所示:
购物车表创建语句如下所示:
CREATE TABLE .(
IDENTITY(1,1) NOT NULL,
NULL,
NULL,
NULL,
(200) NULL,
NULL,
(50) NULL,
NULL,
(50) NULL
) ON
2. 购物车实体创建
购物车实体和数据表结构保持一致,方便进行映射。如下所示:
using SqlSugar;
namespace EasyBuyShop.Models
{
/// <summary>
/// 购物车
/// </summary>
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层代码如下所示:
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.商品详情页面添加购物车】,查询购物车, 删除购物车,代码如下所示:
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>
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>
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购物车视图中,接收控制器传递的参数。如下所示:
@{
var totalPrice = 0.0M;
}
<form action="/Purchase/BuyWithCart" method="post">
<table>
<thead>
<tr>
<th >选择</th>
<th >图片</th>
<th >产品名称</th>
<th >价格</th>
<th >优惠价格</th>
<th >数量</th>
<th >总计</th>
<th >删除</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 >
<input type="checkbox" value="@(cart.Id)" name="chkCart"checked="checked" onchange="javascript:checkCartProduct(this);" />
</td>
<td >
<a target="_blank" href="https://www.cnblogs.com/Product/Detail/@(product.Id)"><img src="https://www.cnblogs.com/@(product.ImageUrl)" alt="" width="100" height="100"></a>
</td>
<td >
<a target="_blank" href="https://www.cnblogs.com/Product/Detail/@(product.Id)">@product.Name</a>
<br />
备注:@(string.IsNullOrEmpty(cart.Remark) ? "无" : cart.Remark)
</td>
<td >@(Math.Round(product.Price, 2))</td>
<td >@(Math.Round(product.PreferentialPrice, 2))</td>
<td >
<input value="@(cart.Quantity)" type="number">
</td>
<td >@(Math.Round(product.PreferentialPrice * cart.Quantity, 2))</td>
<td >
<a target="_blank" href="https://www.cnblogs.com/Cart/Delete/@(cart.Id)">
<i ><font >删除</font></i>
</a>
</td>
</tr>
}
}
else
{
<tr><td colspan="7">购物车暂无商品</td></tr>
}
}
</tbody>
</table>
<ul>
<li >总计@totalPrice</li>
</ul>
<input type="submit" value="购买"onclick="javascript:return checkSubmit();"/>
</form>
购物车页面展示
运行程序,点击登录,在登录成功后,在右上角个人名称,点击下拉菜单,选择购物车,然后打开购物车页面,如下所示:
以上就是ASP.NET Core MVC开发实战之商城系统第五部分内容,后续将继续介绍其他模块,敬请期待。
来源:https://www.cnblogs.com/hsiang/archive/2023/08/03/17602215.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]