MVC3如何在购物车中实现多重“添加到购物车”功能?
问题描述:
我创建了自己的简单购物车,下面是Music store mvc示例。问题是,我的商店一次只允许添加一件商品。但现在我需要一种方法一次将多个物品添加到购物车并指定数量。MVC3如何在购物车中实现多重“添加到购物车”功能?
我在考虑这样做:Model Binding to a List,但我的物料模型没有数量属性来保存所需的购物车数量。
public int ItemID { get; set; }
public string Barcode { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
和我的视图模型:
public class ItemViewModel
{
public int ItemID { get; set; }
public string Barcode { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
}
public class ItemToCartViewModel
{
public List<ItemViewModel> itemToCart { get; set; }
}
似乎
并不在我的岗位动作正确后(null或无值传递):[HttpPost]
public ActionResult addtocart(ICollection<ItemViewModel> items)
{ ... }
任何想法?
UPDATE:
@model IList<MyTGP.ViewModels.ItemViewModel>
@{
ViewBag.Title = "Search for Items";
int count = 0;
}
<h2>
Search for Items</h2>
@Html.Partial("_SearchItemsPartial")
@using (Html.BeginForm("addtocart","Cart"))
{
if (String.IsNullOrEmpty(ViewBag.NoRecord)) {
<table>
<tr>
<th>
Barcode
</th>
<th>
Name
</th>
<th>
Description
</th>
<th>
Price
</th>
<th>
Quantity
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Barcode)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.EditorFor(modelItem => item.Quantity)
</td>
</tr>
count++;
}
</table>
} else { @ViewBag.NoRecord }
<p>
<input type="submit" value="add items to cart" />
</p>
}
答
我无法评论,但所以我在这里发帖。你能向我们展示视图吗? html很重要。
更新: 尝试像这样(在foreach循环)
@Html.Hidden("["+count+"].ItemID",item.ItemID)
@Html.Hidden("["+count+"].Barcode",item.Barcode)
@Html.Hidden("["+count+"].Name",item.Name)
@Html.Hidden("["+count+"].Description",item.Description)
@Html.Hidden("["+count+"].Price",item.Price)
然后在那里你显示正确呈现量@Html.TextBox("["+count+"].Quantity",item.Quantity)
,但一旦我得到我的行动,通过项目为空。 – Ron
更新了我的回答 – MikeSW
感谢您的回答。你能解释为什么隐藏的领域需要? – Ron