Build Shopping Cart with Session in ASP.NET Core MVC


On the Visual Studio, create new ASP.NET Core MVC Web Application project

Select Empty Template

Click Ok button to Finish

Create new folder named images in wwwroot folder. Copy images need to use in project to images folder.




Open Startup.cs file and add new configurations as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreMVCWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSession();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSession();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Demo}/{action=Index}/{id?}");
            });

        }
    }
}

Create new folder named Models. In Models folder, create new entities class as below:

Create new class named Product.cs as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCoreMVCWithRealApps.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public string Photo { get; set; }
    }
}

Create new class named Item.cs as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCoreMVCWithRealApps.Models
{
    public class Item
    {
        public Product Product { get; set; }

        public int Quantity { get; set; }
    }
}




Create new folder named Helpers. In this folder, create new helper named SessionHelper.cs as below:

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCoreMVCWithRealApps.Helpers
{
    public static class SessionHelper
    {
        public static void SetObjectAsJson(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

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

Create new folder named Controllers. In this folder, create new controllers as below:

Create new class named ProductController.cs as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LearnASPNETCoreMVCWithRealApps.Models;
using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreMVCWithRealApps.Controllers
{
    [Route("product")]
    public class ProductController : Controller
    {
        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            ProductModel productModel = new ProductModel();
            ViewBag.products = productModel.findAll();
            return View();
        }
    }
}

Create new class named CartController.cs, this file contains contains the operation methods on the Shopping Cart as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LearnASPNETCoreMVCWithRealApps.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using LearnASPNETCoreMVCWithRealApps.Helpers;

namespace LearnASPNETCoreMVCWithRealApps.Controllers
{
    [Route("cart")]
    public class CartController : Controller
    {
        [Route("index")]
        public IActionResult Index()
        {
            var cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            ViewBag.cart = cart;
            ViewBag.total = cart.Sum(item => item.Product.Price * item.Quantity);
            return View();
        }

        [Route("buy/{id}")]
        public IActionResult Buy(string id)
        {
            ProductModel productModel = new ProductModel();
            if (SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart") == null)
            {
                List<Item> cart = new List<Item>();
                cart.Add(new Item { Product = productModel.find(id), Quantity = 1 });
                SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            }
            else
            {
                List<Item> cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
                int index = isExist(id);
                if (index != -1)
                {
                    cart[index].Quantity++;
                }
                else
                {
                    cart.Add(new Item { Product = productModel.find(id), Quantity = 1 });
                }
                SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            }
            return RedirectToAction("Index");
        }

        [Route("remove/{id}")]
        public IActionResult Remove(string id)
        {
            List<Item> cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            int index = isExist(id);
            cart.RemoveAt(index);
            SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            return RedirectToAction("Index");
        }

        private int isExist(string id)
        {
            List<Item> cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            for (int i = 0; i < cart.Count; i++)
            {
                if (cart[i].Product.Id.Equals(id))
                {
                    return i;
                }
            }
            return -1;
        }

    }
}




Create new folder named Views. In this folder, create new razor views as below:

Create new folder named Product. In Product folder, create new view named Index.cshtml as below:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <h3>Products List</h3>
    <table cellpadding="2" cellspacing="2" border="1">
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Photo</th>
            <th>Price</th>
            <th>Buy</th>
        </tr>
        @foreach (var product in ViewBag.products)
        {
            <tr>
                <td>@product.Id</td>
                <td>@product.Name</td>
                <td><img src="~/images/@product.Photo" width="60" /> </td>
                <td>@product.Price</td>
                <td align="center">
                    <a asp-controller="cart" asp-action="buy" asp-route-id="@product.Id">Buy Now</a>
                </td>
            </tr>
        }
    </table>

</body>
</html>

Create new folder named Cart. In Cart folder, create new view named Index.cshtml as below:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <h3>Cart Page</h3>
    <table cellpadding="2" cellspacing="2" border="1">
        <tr>
            <th>Option</th>
            <th>Id</th>
            <th>Name</th>
            <th>Photo</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Sub Total</th>
        </tr>
        @foreach (var item in ViewBag.cart)
        {
            <tr>
                <td><a asp-controller="cart" asp-action="remove" asp-route-id="@item.Product.Id">Remove</a></td>
                <td>@item.Product.Id</td>
                <td>@item.Product.Name</td>
                <td><img src="~/images/@item.Product.Photo" width="60" /> </td>
                <td>@item.Product.Price</td>
                <td>@item.Quantity</td>
                <td>@(item.Product.Price * item.Quantity)</td>
            </tr>
        }
        <tr>
            <td align="right" colspan="6">Sum</td>
            <td>
                @ViewBag.total
            </td>
        </tr>
    </table>
    <br>
    <a asp-controller="product" asp-action="index">Continue Shopping</a>

</body>
</html>

Select Views folder and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish

In _ViewImports.cshtml file and TagHelpers library as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Access Index action in Product controller with following url: http://localhost:48982

Output

Click Buy Now link from product page to buy a product and show it in cart page

I recommend you refer to the books below to learn more about the knowledge in this article: