【发布时间】:2015-11-26 06:28:15
【问题描述】:
我在我的电子商务 Mvc 应用程序中使用了 Mvc Music Store Shopping Cart。在我在“购物车”表中添加 Size 属性之前,“添加到购物车”功能很好。
我的产品表中有 3 个产品:
- “名称:Polo T恤,数量:40,价格:15,尺码:S,M,L”
- “名称:T恤,数量:20,价格:10,尺码:M,L”
- “名称:衬衫,数量:10,价格:25,尺寸:XS,M,L”
我在下拉列表中显示了这些尺寸,以便用户可以选择尺寸然后添加到购物车。
问题:当我从下拉列表中选择尺寸并点击“添加到购物车”按钮时,它不会将尺寸存储在数据库的“购物车”表中。
查看
@model FypStore.Models.Product
@Html.DropDownListFor(m => m.Size, new SelectList(Model.Size.Split(new char[] { ',' })))
<span>PKR @Html.DisplayFor(model => model.Price)</span>
<br />
<br />
<button type="button" class="btn btn-fefault cart">
<i class="fa fa-shopping-cart"></i>
@Html.ActionLink("Add to cart", "AddToCart", "ShoppingCart", new { id = Model.ProductId }, "")
</button>
控制器我使用了来自 MVc Music Store Example 的完整购物车控制器,所以这里只使用部分控制器。
我已经添加了这一行 string size = "Small"; 并且它工作正常,它将“Small”存储在 Cart 表的 Size 属性中。但我希望从下拉列表中选择这个值。
public ActionResult AddToCart(int id)
{
// Retrieve the album from the database
var addedAlbum = storeDB.Products.Single(prod => prod.ProductId == id);
string size = "Small";
// Add it to the shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedAlbum, size);
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}
ShoppingCart.cs
public void AddToCart(Product product, string size)
{
// Get the matching cart and album instances
var cartItem = storeDB.Carts.SingleOrDefault(
c => c.CartId == ShoppingCartId
&& c.ProductId == product.ProductId);
if (cartItem == null)
{
// Create a new cart item if no cart item exists
cartItem = new Cart
{
ProductId = product.ProductId,
CartId = ShoppingCartId,
Count = 1,
Size = size
};
storeDB.Carts.Add(cartItem);
}
else
{
// If the item does exist in the cart, then add one to the quantity
cartItem.Count++;
}
// Save changes
storeDB.SaveChanges();
}
【问题讨论】:
标签: asp.net asp.net-mvc asp.net-mvc-4