Ron
Ron

Reputation: 1731

MVC3 How to implement a mulitple "add to cart" feature in a shopping cart?

I created my own simple shopping cart following the Music store mvc example. Problem is, my shop only allows one item addition at a time. But now I need a way to add multiple items at once to a cart and specify the quantity.

I was thinking about doing this: Model Binding to a List, but my Item model does not have a quantity property to hold the needed cart quantity.

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; }

and my viewmodel:

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; }
}

doesn't seem to post properly in my post action (null or no values passed):

[HttpPost]
public ActionResult addtocart(ICollection<ItemViewModel> items)
{ ... }

Any ideas?

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>
}

Upvotes: 0

Views: 1947

Answers (1)

MikeSW
MikeSW

Reputation: 16358

I can't comment yet so I'm posting here. Can you show us the view? The html is important.

Update: Try like this (in the foreach loop)

@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)

Then where you display the quantity @Html.TextBox("["+count+"].Quantity",item.Quantity)

Upvotes: 1

Related Questions