【发布时间】:2017-06-11 06:37:51
【问题描述】:
我已经实现了一个类似于购物车的程序,您可以在其中将产品添加到购物车中。我正在使用 ajax 使页面动态化,因此可以将多个产品添加到购物车而无需重新加载页面。由于某种原因,列表中的第一个产品可以正确添加,而其余产品总是在不应该的时候重定向到控制器 url。
查看代码
<section class="grid grid--loading" id="portfoliolist">
<!-- Loader -->
<img class="grid__loader" src="~/Images/grid.svg" width="60" alt="Loader image" />
<!-- Grid sizer for a fluid Isotope (Masonry) layout -->
<div class="grid__sizer"></div>
<!-- Grid items -->
@foreach (var item in Model.ProductsList)
{
var pricetag = "pricegroup3";
if (item.Price <= 300)
{
pricetag = "pricegroup1";
}
else if (item.Price > 300 && item.Price <= 500)
{
pricetag = "pricegroup2";
}
<div class="grid__item @item.Type @pricetag">
<div class="slider">
@foreach (var image in Model.ProductImagesList.Where(m=>m.ProductID == item.Id))
{
<div class="slider__item"><img src="~/Images/Products/@image.Image" /></div>
}
</div>
<div class="meta">
<h3 class="meta__title">@item.Name</h3>
<span class="meta__brand">@item.Brand</span>
<span class="meta__price">R @item.Price</span>
</div>
<a class="action action--button action--buy" href="@Url.Action("AddToPlatform", "ProductPlatforms", new { ProdID = item.Id })" id="platformAdd" data-value="@item.Id"><i class="fa fa-shopping-cart"></i><span class="text-hidden">Add to Platform</span></a>
</div>
}
</section>
最后一个标签将被点击以将产品添加到购物车。
脚本 -Ajax
$("#platformAdd").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr("href"),
success: toastr["success"]("Product added to Platform")
});
});
控制器功能
public void AddToPlatform(int ProdID)
{
var currUser = User.Identity.GetUserId();
DateTime now = DateTime.Now;
var exists = ProductExists(ProdID);
if (exists == false)
{
ProductPlatform prodPlatform = new ProductPlatform()
{
ProductID = ProdID,
UserID = currUser,
ViewedStatus = false,
DateAdded = now
};
db.ProductPlatforms.Add(prodPlatform);
db.SaveChanges();
}
}
ajax 脚本函数将调用控制器函数将产品添加到购物车。由于没有重定向,我似乎无法弄清楚为什么 ajax 调用会重定向到标签“href”。
感谢您的帮助!
【问题讨论】:
-
ID 必须是唯一的。使用(例如)
$(".action--buy").click(...)而不是$("#platformAdd").click(...)。$("#platformAdd")仅返回 ID 为platformAdd的第一个元素 -
你是个传奇。太感谢了。这解决了它。
-
@Andreas - 你为什么不把它作为答案发布?你是第一个回答这个问题的人,你应该得到分数。当前的答案在您发表评论后约 7 小时发布。
-
@Developer 因为我有时必须睡觉,而且因为它是我昨天没有找到的重复;)
标签: javascript jquery ajax asp.net-mvc asp.net-mvc-5