如何解决当我在 asp.net mvc
当我尝试点击添加到购物车按钮时,它不会添加到我的购物车中。我不知道如何解决这个问题。代码是否遗漏了一些重要的东西?我想要这样,当我点击“添加到购物车”时,将添加一个产品,以便它作为添加的项目出现在购物车中。
购物车的查看和 Javascript 代码
@model PagedList.IPagedList<E_Game.viewmodel.ShopVM>
@using PagedList
@using PagedList.Mvc
<!DOCTYPE html>
<html>
<head>
<Meta name="viewport" content="width=device-width" />
<title>User Page</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<link href="~/Content/navbar.css" rel="stylesheet" />
<link href="~/Content/user.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div style=" text-align:center; font-family:Arial; margin-left:177px; margin-top:-10px;font-size:20px;">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div style="float: right; background-color: #fff; float: left; width: 100%; color: #1a1a1a;" class="navbar-collapse collapse">
<p style="text-align:center; margin-bottom:-100px;font-size:50px; font-family:Verdana"> SAVAGE GAME</p>
</div>
</div>
</div>
<div class="container">
<ul class="nav navbar-nav navbar-right">
<li>
@if (Session["CartCounter"] == null)
{
@Html.ActionLink("Cart","ShoppingCart","User",new { id = "cartItem" }) }
else
{
@Html.ActionLink("Cart(" + Session["CartCounter"] + ")",new { id = "cartItem" });
}
</li>
</ul>
<div class="sidebar-container">
<div style="text-align:center;" class="sidebar-logo">
<img style="margin-left:-20px;height:70px; width:200px" src="~/Images/konsol.jpg" />
</div>
<ul class="sidebar-navigation">
<li class="header">Navigation</li>
<li>
<a href="#">
<i class="fa fa-home" aria-hidden="true"></i> Homepage
</a>
</li>
<li>
<a href="#">
<i class="fa fa-tachometer" aria-hidden="true"></i> About
</a>
</li>
<li>
<a href="#">
<i class="fa fa-tachometer" aria-hidden="true"></i> Contact
</a>
</li>
<li class="header">Shopping</li>
<li>
<a href="#">
<i class="fa fa-users" aria-hidden="true"></i> Categories
</a>
</li>
<li>
<a href="#">
<i class="fa fa-cog" aria-hidden="true"></i> Products
</a>
</li>
<li class="header">Settings</li>
<li>
<a href="#">
<i class="fa fa-info-circle" aria-hidden="true"></i> User
</a>
</li>
<li>
<a href="#">
<i class="fa fa-info-circle" aria-hidden="true"></i> Log Out
</a>
</li>
</ul>
</div>
<div class="content-container">
<div class="container-fluid">
</div>
<div class="olContent f1"><h2 style="color:black">Search Product/Category</h2></div>
<div class="olSearch fr">
<input type="text" placeholder="Enter Keyword" name="searchKey" class="inputComn houseText form-control" />
<div class="searchIcon">
<button type="button" class="searchBtn">
<img src="~/Images/searchIcon.png" />
</button>
</div>
<!-- Main component for a primary marketing message or call to action -->
<div style="background-color:white; " class="jumbotron">
@foreach (var item in Model)
{
<div class="col-md-2" style="border:1px solid black; margin:15px; width:200px;">
<div style="text-align:center; border-bottom: 1px dashed solid; ">
<h4> @item.ProductName</h4>
</div>
<div>
<div class="col-md-10" style=" margin-left:-10px">
<img src="@Url.Content(item.Image)" width="150" height="250" />
<div style="text-align:center; margin-top:15px;">
<a style=" margin-left:35px">@item.Price.ToString("#,## $")</a>
<br />
<a style="margin-left:35px;">@Html.ActionLink("Description","Description","Shop")</a>
<br />
<div style="float:left; font-size:7px; color:#65a0c9;">
//add to cart button
<button type="button" name="AddToCart" value="Add To Cart" class="btn btn-primary" itemid="@item.ProductId" id="btnAddToCart" onclick="AddToCart(this)">Add To Cart</button>
</div>
</div>
</div>
</div>
</div>}
<br />
<br />
<br />
<div style="float:left; margin-top:450px; margin-left:-650px; ">
@Html.PagedListPager((IPagedList)Model,page => Url.Action("Index",new { page }))
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
function AddtoCart(item) {
var ProductId = $(item).attr("itemid");
var formData = new FormData();
formData.append("ProductId",itemid);
$.ajax(
{
async: true,type: 'POST',contentType: false,processData: false,data: formData,url: '/User/Index',success: function (data) {
if (data.Success) {
$("#CartProduct").text("Cart(" + data.Counter + ")");
}
},error: function () {
alert("We can not added your product.");
}
});
}
</script>
用于创建添加到购物车事件和索引的控制器
using E_Game.Models;
using E_Game.viewmodel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using PagedList.Mvc;
using PagedList;
using E_Game.Repository;
using System.Data.sqlClient;
using Newtonsoft.Json;
namespace E_Game.Controllers
{
public class UserController : Controller
{
// GET: User
// GET: Shop
GameSalesSystemEntities db = new GameSalesSystemEntities();
private GameSalesSystemEntities objgameSalesSystemEntities;
List<ShoppingCartModel> listofShoppingCartModels;
public UserController()
{
objgameSalesSystemEntities = new GameSalesSystemEntities();
listofShoppingCartModels = new List<ShoppingCartModel>();
}
public ActionResult Index(int page = 1)
{
IEnumerable<ShopVM> listofShopVMs = (from objProduct in objgameSalesSystemEntities.Products
join objCategory in objgameSalesSystemEntities.Categories
on objProduct.CategoryId equals objCategory.CategoryId
select new ShopVM()
{
Image = objProduct.Image,ProductName = objProduct.ProductName,PDescription = objProduct.PDescription,Price = objProduct.Price,ProductId = objProduct.ProductId,Category = objCategory.CategoryName,ProductCode = objProduct.ProductCode
}).ToList().ToPagedList(page,8);
return View(listofShopVMs);
}
[HttpPost]
public JsonResult Index(string ProductId)
{
ShoppingCartModel objShoppingCartModel = new ShoppingCartModel();
Products objProduct = objgameSalesSystemEntities.Products.Single(model => model.ProductId.ToString() == ProductId);
if (Session["CartCounter"] != null)
{
listofShoppingCartModels = Session["CartProduct"] as List<ShoppingCartModel>;
}
if (listofShoppingCartModels.Any(model => model.ProductId == ProductId))
{
objShoppingCartModel = listofShoppingCartModels.Single(model => model.ProductId == ProductId);
objShoppingCartModel.Quantity = objShoppingCartModel.Quantity + 1;
objShoppingCartModel.Total = objShoppingCartModel.Quantity * objShoppingCartModel.UnitPrice;
}
else
{
objShoppingCartModel.ProductId = ProductId;
objShoppingCartModel.Image = objProduct.Image;
objShoppingCartModel.ProductName = objProduct.ProductName;
objShoppingCartModel.Quantity = 1;
objShoppingCartModel.UnitPrice = objProduct.Price;
objShoppingCartModel.Total = objProduct.Price;
listofShoppingCartModels.Add(objShoppingCartModel);
}
Session["CartCounter"] = listofShoppingCartModels.Count;
Session["CartProduct"] = listofShoppingCartModels;
return Json(new { Success = true,Counter = listofShoppingCartModels.Count },JsonRequestBehavior.AllowGet);
}
public ActionResult ShoppingCart()
{
listofShoppingCartModels = Session["CartProduct"] as List<ShoppingCartModel>;
return View(listofShoppingCartModels);
}
}
}
解决方法
您的 JavaScript 代码中有许多错误。
首先,您将按钮的 onclick 属性设置为 AddToCart(this)
,但在您的 JavaScript 代码中,该函数名为 AddtoCart
(带有小写的 t)。
其次,您在行中创建了一个名为 ProductId
的变量:
var ProductId = $(item).attr("itemid");
但后来引用了一个名为 itemid
(它不存在)的变量:
formData.append("ProductId",itemid);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。