locked
Deleting From Cart using cookies RRS feed

  • Question

  • User-1473429353 posted

    Hi, I am looking for a way to delete an item from my cart using cookies. I have this code to add to the cart. I am unsure of how to use it to delete the relevant item.

    Here is the code related to my cookie and add to cart button on the stock page:

     protected void AddToCartBtn_Click(object sender, EventArgs e)
            {
    
                HttpCookie cookie = Request.Cookies["Cart"];
                string id = Request.QueryString["StockID"].ToString();
                string previousCookieValue = "";
                List<string> ids = new List<string>();
    
                //Save the cookie value to a string for future reference
                if (cookie != null)
                {
                    previousCookieValue = cookie.Value;
                }
    
                //Re-create the cookie, so we don't have any of the old properties
                cookie = new HttpCookie("Cart");
    
                //Try and deserialize the previous cookie value to the list of strings we currently use.
                try
                {
                    ids = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(previousCookieValue);
                }
                catch (Exception ex)
                {
    
                }
    
                ids.Add(id); //Add new ID to the list
    
    
                cookie.Value = Newtonsoft.Json.JsonConvert.SerializeObject(ids);
                cookie.Expires = DateTime.Now.AddDays(30);
    
                Response.Cookies.Add(cookie);
    
                
            }

    Here is the code for my cart page:

     protected void Page_Load(object sender, EventArgs e)
            {
    
                HttpCookie cookie = Request.Cookies["Cart"];
                if (cookie != null)
                {
                    List<string> idVals = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(cookie.Value);
                    
        
                    List<Car> cars = new List<Car>();
    
                    foreach (string item in idVals)
                    {
                        DataTable dt = new DataTable();
                        Console.WriteLine(item);
                        try
                        {
                            using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbCore"].ToString()))
                            {
                                string SQL = "SELECT tblStock.Stock_ID, tblMake.Make, tblModel.Model, tblColour.Colour, tblStock.Price, tblStock.Picture FROM (((tblStock INNER JOIN tblMake ON tblStock.Make_ID = tblMake.Make_ID) INNER JOIN tblModel ON tblStock.Model_ID = tblModel.Model_ID) INNER JOIN tblColour ON tblStock.Colour_ID = tblColour.Colour_ID) WHERE tblStock.Stock_ID = " + item;
                                SqlCommand myCommand = new SqlCommand(SQL, cn);
                                SqlDataAdapter da = new SqlDataAdapter() { SelectCommand = myCommand };
                                da.Fill(dt);
                                da.Dispose();
    
    
                                foreach (DataRow dr in dt.Rows)
                                {
                                    var car = new Car();
                                    car.Make = dr["Make"].ToString();
                                    car.Model = dr["Model"].ToString();
                                    car.Colour = dr["Colour"].ToString();
                                    car.Price = dr["Price"].ToString();
                                    car.Image = (byte[]) dr["Picture"];
                                    cars.Add(car);
                                }
    
    
                            }
    
                        }
    
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.ToString());
                        }
    
                    }
                    Repeater1.DataSource = cars;
                    Repeater1.DataBind();
    
                }
    
                else
                {
                    LblEmpty.Text = "Car is empty. Please select a product to add to cart";
                }
            }

    This code works to display the items, there is a delete icon next to each item in the cart. whenever this button is clicked i would like to remove the relevant item from the cookie. How would I go about doing this?

    Thursday, October 1, 2020 2:17 PM

All replies

  • User475983607 posted

    The "Cart" cookies contains a list of string.  It's a simple matter of removing the item from the List<string>; https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.remove?view=netcore-3.1.

    List<string> idVals = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(cookie.Value);
    idVals.Remove(theIdToRemove);

    Or RemoveAll.

    Then just set the cookie like you did to create the  cookie in the first place.

    Thursday, October 1, 2020 3:02 PM
  • User1535942433 posted

    Hi Faiiza,

    As far as I think, you are not required to delete a cookie if you want to update it's value. Just send back the updated cookie with its new properties (value, time etc.) and the existing cookie on the client will be updated.

    More details,you could refer to below article:

    https://stackoverflow.com/questions/48857592/deleting-specific-key-values-from-cookie-in-c-sharp

    Best regards,

    Yijing Sun

    Friday, October 2, 2020 5:59 AM
  • User-1473429353 posted

    But how do I get the id of the item in the list which the delete button was clicked for? Because I have a separate button on_click event for the delete. I'm unsure of how to get the id in this function.

    Friday, October 2, 2020 8:06 AM
  • User475983607 posted

    But how do I get the id of the item in the list which the delete button was clicked for? Because I have a separate button on_click event for the delete. I'm unsure of how to get the id in this function.

    Share the "delete" code.  

    Friday, October 2, 2020 11:31 AM
  • User-1473429353 posted
            protected void BtnDelete_Command(object sender, CommandEventArgs e)
            {
                HttpCookie cookie = Request.Cookies["Cart"];
                if (cookie != null)
                {
                    List<string> idVals = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(cookie.Value);
                    idVals.Remove();
    
                    ListView1.DataSource = idVals;
                    ListView1.DataBind();
    
    
    
                    //Page.Response.Redirect(Page.Request.Url.ToString(), true);
    
                }
            }   

    Here's the delete command code. The data is now in a ListView and each row has a delete button next to it., however I'm unsure of how to specifically delete that row (not sure what to put inside the remove brackets).

    Friday, October 2, 2020 1:57 PM
  • User475983607 posted

    You did not share all the relevant code so it is hard to provide an accurate solution.  The community needs the markup too.  The code indicates you are not following Web Forms standards found in beginning level tutorials.  A delete action is typically handled by the ItemCommand event the ListView not a button event.  Please go through the following tutorial to learn how to work with data bound controls.

    https://www.c-sharpcorner.com/UploadFile/b926a6/insert-select-edit-delete-record-using-Asp-Net-listview/

    Friday, October 2, 2020 3:30 PM