2011-11-01 145 views
0

我創建了自己的簡單購物車,下面是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> 
} 

回答

1

我無法評論,但所以我在這裏發帖。你能向我們展示視圖嗎? 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)

+0

,但一旦我得到我的行動,通過項目爲空。 – Ron

+0

更新了我的回答 – MikeSW

+0

感謝您的回答。你能解釋爲什麼隱藏的領域需要? – Ron

相關問題