locked
Cookie and serialisation RRS feed

  • Question

  • User-1473429353 posted

    Hi,

    I'm making a car purchasing website just for practice and have to make an add to cart feature using cookies. I want to set the car id as the cookie in the add to cart button but then in the cart.aspx.cs I want to use this id cookie to get the details related to the car from the database (image, make, model, colour and price). 

    I have this code on my product page for the add to stock button which my manager helped me with:

            protected void AddToCartBtn_Click(object sender, EventArgs e)
            {
    
                HttpCookie cookie = new HttpCookie("ShoppingCart");
                cookie["ID"] = Newtonsoft.Json.JsonConvert.SerializeObject(cookie);
                cookie.Expires = DateTime.Now.AddDays(30);
                Response.Cookies.Add(cookie);
                Response.Redirect("Cart.aspx");
    
            }

    I am not sure if this is right and I also don't know what to add to the cart.aspx.cs to get the data from the database using the cookie and save them in my labels. If someone could make this a bit clearer for me to understand that would be great.

    Tuesday, September 29, 2020 10:08 AM

All replies

  • User475983607 posted

    Typically, the ID is passed in the URL.  Also, if this is a learning exercise you should use a modern framework like MVC or Razor Pages.

    Tuesday, September 29, 2020 10:42 AM
  • User-1473429353 posted

    It's a learning exercise but the company want me to use asp.net c# web forms, can't use anything else 

    Tuesday, September 29, 2020 10:45 AM
  • User475983607 posted

    Your original code does not make sense.  If you already have a cookie with the ID then why are you creating another cookie with the same information.  Just read the cookie in Cart.aspx.

    Anyway, a common method passing an ID in the URL.

    Response.Redirect("Cart.aspx?id=" + theId.ToString());

    Then in the Cart.aspx page get the ID.

    string ID = Request["ID"]

    Tuesday, September 29, 2020 11:03 AM