Search code examples
asp.net-mvcsessionshopping-cart

retrieve session value in view page


i just started to learn how to build a website, and i have some problem with using session to create a shopping cart.

Here is my model code:

public class Cart
{
    public Cart()
    {
        Products = new List<ProductStock>();
    }

    public List<ProductStock> Products { get; set; }

    public void AddToCart(Product product, Store store, int quantity)
    {
        Products.Add(new ProductStock
        {
            ProductID = product.ProductID,
            Product = product,
            StoreID = store.StoreID,
            Store = store,
            Quantity = quantity
        });
    }
}

Here is controller code, the session i want to use in the view page is called "cart":

public class CartController : Controller
{
    private MagicInventoryEntities db = new MagicInventoryEntities();

    public ActionResult Index()
    {
        Cart cart = (Cart) Session["cart"];

        return View(cart);
    }

    [HttpPost]
    public ActionResult AddToCart(int productID, int storeID, int quantity)
    {
        Product product = db.Products.Find(productID);
        Store store = db.Stores.Find(storeID);

        Cart cart = (Cart) Session["cart"];

        cart.AddToCart(product, store, quantity);

        return new RedirectToRouteResult(new RouteValueDictionary(
        new
        {
            action = "Index",
            controller = "Cart"
        }));
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

This code is from my teacher, my notes were not very clear and i didn't have enough time to write the details about the view page. He said he will show the process again on Monday, i just don't want to wait, i want to figure it out and move on. I only know the basic method to call a session is "@session["SessionName"].ToString() ". I have tried it in my method( session["testing"]=ProductID ), and i can get the value. However, i don't how to get value from Session["cart"].


Solution

  • Assuming you have an object of type Cart saved in your session, in order to retrieve that object you can use the following code in your Index view:

     @{
        Cart cart = HttpContext.Current.Session["Cart"] as Cart;
      }
    

    However, I see that your Index method in your CartController already retrieves the object from the Session and passes it to the Index view. In order to access it you have to write the following code in your Index View:

    @model {ProjectName}.Models.Cart  //you tell the View what type of object it should expect to receive; instead of {ProjectName} write your project name
    
    
    @foreach(var product in Model.Products) {  //you access the received object by using the keyword Model
        <div>
            @product.ProductId
        </div>
    }
    

    As you can see, this examples creates a div for each item of type ProductStock in your Products List, and writes the value of the current ProductStock ProductId inside of it.

    If you do not have an object of type Cart saved in your Session, you could add the following code to your Index method:

    if(Session["Cart"] == null)
    {
        var cart = new Cart();
        Session["Cart"] = cart;
    }
    
    Cart cart = (Cart) Session["cart"];
    return View(cart);