0

I am trying to delete a list of products serialized as a Json object in a session but I am not sure how to go about it. Basically, I want to be able to delete a list of products once a user presses the cancels order button.

Here is where and how I initially set and serialized the session string and Json object respectively


public IActionResult OrderProduct(){

    ProductViewModel productViewModel = new ProductViewModel();

    return View(productViewModel);
}

[HTTPPost]
public IActionResult OrderProduct(ProductViewModel productViewModel){

    Product product  = new Product();
    product.Id = productViewModel.Id;

    List<Product> products = new List<Product>();
    products.Add(product);

    HttpContext.Session.SetString("SessionProducts", JsonConvert.SerializeObject(products));
    returnToRedirect("ConfirmOrder");
}

[HTTPPost]
public IActionResult ConfirmOrder(){

var products= JsonConvert.DeserializeObject<List<Product>>(HttpContext.Session.GetString("SessionProducts"));

    foreach(var product in products){
       _productRepo.CreateOrder(product) //stores product in the database
    }

return RedirectToAction("OrderSummary");

}

Once the user clicks the cancel order button, I have them redirected to this HTTPGET Action method below. Here, I was hoping to able to delete the session and the Json object so that the user can start all over to create a new order of products

public IActionResult UserMenu(){
    if (HttpContext.Session.GetString("SessionProducts") != null){
/*
    dynamic products= JsonConvert.DeserializeObject<List<Product>>(HttpContext.Session.GetString("SessionProducts"));
            JObject jObject = JObject.Parse(products);
            jObject.RemoveAll();
*/
    HttpContext.Session.Remove("SessionProducts");
    }
    return View();
}

The problem is that HttpContext.Session.Remove("SessionProducts") is not doing what I thought it would do (which is, to delete the session). I know this because when I try to persist the list of products in my database, it persists both the ones it was supposed to have deleted and the new add products. I now know that I HttpContext.Session.Remove("SessionProducts") does not necessarily delete the session, but rather removes the key string. However, problem not is how can I delete both the session and the json object? How do I get this done the right way?

user8964654
  • 87
  • 1
  • 9
  • instead of removing it, have you tried clearing it - .Clear("SessionProducts"), better yet: HttpContext.Session.Clear() – Jawad Dec 10 '19 at 03:46
  • Please review [MCVE] guide on posting code - the code in the post seem to be doing exactly what you want... So there is a good chance that your actual problem is somewhere else. You need tp [edit] post so it actually demonstrates some problem - currently post simply shows an answer to the question asked on the title. – Alexei Levenkov Dec 10 '19 at 03:55

0 Answers0