0

I need some help. I have written code in MVC 5 .NET Framework where I used session to store my cart items list. It was pretty straight forward but now I am rewriting the code in ASP.NET MVC CORE 6 for another project but it is not working the way I was expecting. Scenario: I have a List of items as below:

private List<SalesCartItemsModel>? itemsList; //Shopping Cart

        public SalesController()
        {
            itemsList = new List<SalesCartItemsModel>();
        }

I want to use Session to store my Cart Items. I used this simple syntax:

Session["cartItems"] = null;
if (Session["cartItems"] != null)
                {
                    itemsList = (List<PurchaseCartItem>)Session["cartItems"];
                }
Session["cartItems"] = itemsList;

Now when i try to use the same in MVC CORE 6, it seems it doesnt support this syntax anymore. What i have tried so far is

HttpContext.Session.SetString("cartItems", itemsList)

But it throws error and does not accept it. ERROR:

cannot convert from 'System.Collections.Generic.List<.Models.SalesCart.SalesCartItemsModel>' to 'string'

Please help me how can I achieve the same in MVC Core? How can I change the code in the current syntax to MVC CORE 6.0?

Omer
  • 133
  • 1
  • 2
  • 16
  • [Here](https://stackoverflow.com/questions/55220812/how-to-store-and-retrieve-objects-in-session-state-in-asp-net-core-2-x) is a solution where they wrote their own extension on `ISession` that handled converting to and from JSON – Jonesopolis Jun 09 '22 at 18:13
  • @Jonesopolis thanks for responding my question. Actually my confusion is that SetString() accepts two parameters i.e. string and a value but its not taking itemList as I mentioned in the question. I want to store Items List not only single string value. – Omer Jun 09 '22 at 18:18
  • @Omer List isnt a String, so you are going to have to convert it to JSON if you want to use `SetString()`. – mxmissile Jun 09 '22 at 18:22
  • @mxmissile and how can we check in this scenario that whether the session is null or not? as i have mentioned in my question. – Omer Jun 10 '22 at 03:28

1 Answers1

2

Maybe this is what you want to know:

Models:

public class SalesCartItemsModel
{
        public string ShopId { get; set; }
        public string ShopName { get; set; }
}
public class PurchaseCartItem
{
        public string ShopId { get; set; }
        public string ShopName { get; set; }
}

SessionExtensions:

public static class SessionExtensions
{
        public static void Set<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonSerializer.Serialize(value));
        }

        public static T Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default : JsonSerializer.Deserialize<T>(value);
        }
}

Program:

builder.Services.AddSession();
app.UseSession();

Controller:

private List<SalesCartItemsModel>? itemsList;
private List<PurchaseCartItem>? itemListP;

public JsonResult Test()
{
            itemsList = new List<SalesCartItemsModel>();
            itemsList.Add(new SalesCartItemsModel { ShopId = "1", ShopName = "Apple" });
            itemsList.Add(new SalesCartItemsModel { ShopId = "2", ShopName = "Banana" });
            HttpContext.Session.Set<List<SalesCartItemsModel>>("cartItems", itemsList);
            var value = HttpContext.Session.Get<List<SalesCartItemsModel>>("cartItems");
            return Json(value);
}

Result:

enter image description here

When you don't store the value in the session, you can judge value=null to store the new value for the session:

public JsonResult Test()
{
            itemsList = new List<SalesCartItemsModel>();
            //itemsList.Add(new SalesCartItemsModel { ShopId = "1", ShopName = "Apple" });
            //itemsList.Add(new SalesCartItemsModel { ShopId = "2", ShopName = "Banana" });
            //HttpContext.Session.Set<List<SalesCartItemsModel>>("cartItems", itemsList);
            var value = HttpContext.Session.Get<List<SalesCartItemsModel>>("cartItems");
            if (value == null)
            {
                itemListP = new List<PurchaseCartItem>();
                itemListP.Add(new PurchaseCartItem { ShopId = "1", ShopName = "Orange" });
                itemListP.Add(new PurchaseCartItem { ShopId = "2", ShopName = "Pear" });
                HttpContext.Session.Set<List<PurchaseCartItem>>("cartItems", itemListP);
                var valueP = HttpContext.Session.Get<List<PurchaseCartItem>>("cartItems");
                return Json(valueP);
            }
            else
            {
                return Json(value);
            }
}

Result:

enter image description here

When there is no value in your itemsList, you can judge value.Count=0 to add a new value to the session:

public JsonResult Test()
{
            itemsList = new List<SalesCartItemsModel>();
            //itemsList.Add(new SalesCartItemsModel { ShopId = "1", ShopName = "Apple" });
            //itemsList.Add(new SalesCartItemsModel { ShopId = "2", ShopName = "Banana" });
            HttpContext.Session.Set<List<SalesCartItemsModel>>("cartItems", itemsList);
            var value = HttpContext.Session.Get<List<SalesCartItemsModel>>("cartItems");
            if (value.Count == 0)
            {
                itemListP = new List<PurchaseCartItem>();
                itemListP.Add(new PurchaseCartItem { ShopId = "1", ShopName = "Orange" });
                itemListP.Add(new PurchaseCartItem { ShopId = "2", ShopName = "Pear" });
                HttpContext.Session.Set<List<PurchaseCartItem>>("cartItems", itemListP);
                var valueP = HttpContext.Session.Get<List<PurchaseCartItem>>("cartItems");
                return Json(valueP);
            }
            else
            {
                return Json(value);
            }
}

Result:

enter image description here

Chen
  • 4,499
  • 1
  • 2
  • 9
  • Thank you vey much your answer helped me a lot. BTW how can I keep the session active even if the user refreshes the page the cart should keep the items? – Omer Jun 10 '22 at 10:08
  • Because currently the cart gets empty when I refresh the page. – Omer Jun 10 '22 at 10:34
  • 1
    You can refer to this [document](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-6.0). – Chen Jun 13 '22 at 09:08