frc
frc

Reputation: 588

Edit and delete a specific view model in a list

I am making a shopping cart and for keeping track of the cart I have a session which contains a list of product view models.

This is the action method for adding to cart:

public ActionResult AddToCart(string id)
        {
            List<CartVM> cartVMList = new List<CartVM>();
            CartVM cartVM = new CartVM();

            int productId = Int32.Parse(id);

            Db db = new Db();

            var result = db.Products.FirstOrDefault(x => x.Id == productId);
            decimal price = result.Price;

            cartVM.ProductId = productId;
            cartVM.Quantity = 1;
            cartVM.Price = price;

            if (Session["cart"] != null)
            {
                cartVMList = (List<CartVM>)Session["cart"];
                cartVMList.Add(cartVM);
            }
            else
            {
                cartVMList.Add(cartVM);
            }

            Session["cart"] = cartVMList;

            //return Content(id);
            return RedirectToAction("Index", "ShoppingCart");
        }

It works when adding new products, so e.g. if I add 5 new products the session will contain a list of 5 products, but how do I edit and delete a specific view model from the list, based on for example the ProductId ?

Upvotes: 0

Views: 110

Answers (1)

James Haug
James Haug

Reputation: 1497

I haven't tested it, but the following should work. All you need to do is grab the cart list like you did when adding to cart. Instead of adding a new item, you just edit the object in the list or remove it from the list.

Technically, unless Session does something special, you shouldn't need to re-save the list to the Session if you got it from the session, since a list is a reference type.

public ActionResult EditCartItem(string id, int quantity, decimal price)
{
    if (Session["cart"] != null)
    {
        var cartVMList = (List<CartVM>) Session["cart"];
        var itemToEdit = cartVMList.FirstOrDefault(cartVM => cartVM.Id == id);
        if(itemToEdit == null)
            return this.HttpNotFound();
        itemToEdit.Quantity = quantity;
        itemToEdit.Price = price;           
    }
}
public ActionResult RemoveFromCart(string id)
{
    if (Session["cart"] != null)
    {
        var cartVMList = (List<CartVM>) Session["cart"];
        var itemToRemove = cartVMList.FirstOrDefault(cartVM => cartVM.Id == id);
        if(itemToRemove == null)
            return this.HttpNotFound();
        cartVMList.Remove(itemToRemove);
    }
}

Upvotes: 0

Related Questions