Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Please can anybody help me to add and retrieve list data to a Session in MVC Core

public ActionResult OrderNow(int id)
     {
         if (HttpContext.Session.GetString("AnansiCart") ==null)
         {
             List<Item> cart = new List<Item>();
             cart.Add(new Item(_productResipory.GetByID(id),1));

           <<Need to add "cart to a session">>

         }
         else
         {

         }

         return View("Cart");
     }


What I have tried:

public ActionResult OrderNow(int id)
{
    if (HttpContext.Session.GetString("AnansiCart") ==null)
    {
        List<Item> cart = new List<Item>();
        cart.Add(new Item(_productResipory.GetByID(id),1));


        HttpContext.Session.SetObjectAsJson("AnansiCart", cart);
    }
    else
    {

    }

    return View("Cart");
}

But dont know how to retrieve it on my web page
Posted
Updated 31-May-17 10:38am

1 solution

Session state in ASP.NET Core is significantly different to previous versions of ASP.NET, but it's not too complicated to work with:
Using Sessions and HttpContext in ASP.NET Core and MVC Core[^]
C#
// Get the cart from the session; if it doesn't exist, create a new one:
List<Item> cart = HttpContext.Session.GetObjectFromJson<List<Item>>("AnansiCart") ?? new List<Item>();

// Modify the cart:
cart.Add(...);

// Store the modified cart:
HttpContext.Session.SetObjectAsJson("AnansiCart", cart);

NB: Unlike previous versions of ASP.NET, updates to complex objects are not automatically stored. You'll need to call the SetObjectAsJson extension method after you've finished making your modifications.

For simplicity, you might want to declare a façade to encapsulate the session access:
C#
public static class CartExtensions
{
    private const string CartSessionKey = "AnansiCart";
    
    public static List<Item> GetCart(this ISession session)
    {
        return session.GetObjectFromJson<List<Item>>(CartSessionKey) ?? new List<Item>();
    }
    
    public static void SaveCart(this ISession session, List<Item> cart)
    {
        session.SetObjectAsJson(CartSessionKey, cart);
    }
}

That way, the key is only stored once, avoiding the possibility of typos, and you don't have to keep repeating the same code:
C#
List<Item> cart = HttpContext.Session.GetCart();

cart.Add(...);

HttpContext.Session.SaveCart(cart);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900