Reputation: 29
I want to delete a specific item from 'Session'. My code is:
public ActionResult DeleteProductFromCart(AddToCart id)
{
MyDBContext myDBContext = new MyDBContext();
List<AddToCart> cart = (List<AddToCart>)Session["cart"];
cart.RemoveAt(Convert.ToInt16(cart.Contains(id)));
return RedirectToAction("ViewCart");
}
But this is not working properly.
Upvotes: 1
Views: 86
Reputation: 729
Assuming you have an id property in AddToCart
Class
First you have to retrieve carts from session
List<AddToCart> cart = (List<AddToCart>)Session["cart"];
After that you have to get cart associated with id
AddToCart itemToDelete=cart.FirstorDefault(x=>x.id==id.id);
Finally you can delete like this...
cart.Remove(itemToDelete);
Upvotes: 1
Reputation: 9242
cart.Contains(id)
will return a boolean, not the index of the item that you want to remove.
You will need to make some adjustments similar to the following code(assuming that your AddToCart
class has an Id field):
1- rename your passed parameter for better readability
public ActionResult DeleteProductFromCart(AddToCart item)
2- get the item (if it does exist in your collection):
var itemToBeRemoved = cart.SingleOrDefault(i=>i.Id == item.Id);
// if the item exists, remove it from the cart collection
if(itemToBeRemoved!=null)
{
cart.remove(itemToBeRemoved);
}
Upvotes: 1