Bilal Mustafa
Bilal Mustafa

Reputation: 29

Delete specific value from Session

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

Answers (2)

mukesh kudi
mukesh kudi

Reputation: 729

Assuming you have an id property in AddToCart Class

  1. First you have to retrieve carts from session

    List<AddToCart> cart = (List<AddToCart>)Session["cart"];
    
  2. After that you have to get cart associated with id

    AddToCart itemToDelete=cart.FirstorDefault(x=>x.id==id.id);
    
  3. Finally you can delete like this...

    cart.Remove(itemToDelete);
    

Upvotes: 1

Mohammed Swillam
Mohammed Swillam

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

Related Questions