简体   繁体   中英

How to save session values of shopping cart in database using asp.net + MVC

So this is my code for add to cart. Now i wish to save the session objects in database. Can someone explain to me how should i proceed with it

public ActionResult Cart(int id)
    {
        if (Session["cart"] == null)
        {
            var cart = new List<Item>();              
            cart.Add(new Item(_productService.GetProductById(id), 1));
            Session["cart"] = cart;
        }
        else
        {
            var cart = (List<Item>)Session["cart"];
            int index = isExisting(id);
            if (index == -1)
            {
                cart.Add(new Item(_productService.GetProductById(id), 1));
            }
            else
            {
                cart[index].Quantity++;
            }
            Session["cart"] = cart;
        }
        var userModel = new UserViewModel(true, null, null);
        return View(userModel);
    }

There are several methods to save data to a databbase via ASP.NET.

I recommend you look into using an Object-Relational Mapping tool:

  1. NHibernate (with FluentNHibernate)
  2. EntityFramework

There is a plethora of documentation resources for each of these tools.

You can also resort to using ADO.NET, but this is not recommended unless you absolutely have to use it.

I deal with this exact scenario. One option is to serialize your cart as XML and store the XML in a database column. This approach is useful if you don't expect that you'll need to query the specifics of the object - you just want to save and restore it, which is what you're doing with Session. The downside is that you could lose some backwards compatibility if you modify the class or classes that make up a cart.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM