【发布时间】:2018-05-02 16:47:50
【问题描述】:
我在我的产品详细信息视图中创建了一个下拉列表,它有 5 个硬编码值 (1,2,3,4,5),当我选择想要的值时,我将其传递给ShoppingCart 控制器,然后当我单击添加到购物车按钮时进入购物车模型的同名方法,但是当我将商品添加到购物车时,数量显示为 0。
我的产品详情视图:
@model BigVisionGames.Models.Products
@{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>Product: @Model.ProductName</h3>
<div id="product-details">
<p>
<em>Price: </em>
£@($"{Model.Price:F}")
</p>
<div style="color:black">
@Html.DropDownListFor(model => model.ChosenQuantity, new
List<SelectListItem>
{
new SelectListItem{ Text="1", Value = "1" },
new SelectListItem{ Text="2", Value = "2" },
new SelectListItem{ Text="3", Value = "3" },
new SelectListItem{ Text="4", Value = "4" },
new SelectListItem{ Text="5", Value = "5" }
})
@Html.ValidationMessageFor(model => model.ChosenQuantity, "", new { @class = "text-danger" })
</div>
@if (Model.StockLevel == 0)
{
<p style="color:red">This item is currently out of stock!</p>
}
else
{
<p class="btn">
@Html.ActionLink("Add to cart", "AddToCartWithQuantity", "ShoppingCart", new { id = Model.Id}, "")
</p>
}
ShoppingCartController 方法
public ActionResult AddToCartWithQuantity(int id, Products productModel)
{
// Retrieve the product from the database
var addedproduct = storeDB.Products
.Single(product => product.Id == id);
// Add it to the shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCartWithQuantity(addedproduct, productModel.ChosenQuantity);
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}
ShoppingCart Model 设置所选数量的方法
public void AddToCartWithQuantity(Products product, int chosenQuantity)
{
// Get the matching cart and product instances
var cartItem = storeDB.Carts.SingleOrDefault(
c => c.CartId == ShoppingCartId
&& c.ProductId == product.Id);
if (cartItem == null)
{
// Create a new cart item if no cart item exists
cartItem = new Cart
{
ProductId = product.Id,
CartId = ShoppingCartId,
Quantity = chosenQuantity,
DateCreated = DateTime.Now
};
storeDB.Carts.Add(cartItem);
}
else
{
// If the item does exist in the cart,
// then add one to the quantity
cartItem.Quantity++;
}
// Save changes
storeDB.SaveChanges();
}
【问题讨论】:
-
您当前的代码不能满足您的要求。它呈现一个锚标记。您需要提交表单或 ajax 发布或发送到操作方法。
-
你的表格在哪里?
标签: c# asp.net-mvc