Build Shopping Cart with Session in ASP.NET Core Razor Pages

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

Select Empty Template

Click Ok button to Finish




Create new folder named wwwroot

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 Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreRazorPagesWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSession();

            services.AddMvc();
        }

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

            app.UseStaticFiles();

            app.UseSession();

            app.UseMvc();
        }
    }
}




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

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

Create new class named Product.cs as below:

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

Create new class named Item.cs as below:

namespace LearnASPNETCoreRazorPagesWithRealApps.Entities
{
    public class Item
    {
        public Product Product { get; set; }

        public int Quantity { get; set; }
    }
}




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

Create new class named ProductModel.cs as below:

using LearnASPNETCoreRazorPagesWithRealApps.Entities;
using System.Collections.Generic;
using System.Linq;

namespace LearnASPNETCoreRazorPagesWithRealApps.Models
{
    public class ProductModel
    {
        private List<Product> Products;

        public ProductModel()
        {
            Products = new List<Product>() {
                new Product
                {
                    Id = "p01",
                    Name = "name 1",
                    Price = 4,
                    Photo = "thumb1.gif"
                },
                new Product
                {
                    Id = "p02",
                    Name = "name 2",
                    Price = 2,
                    Photo = "thumb2.gif"
                },
                new Product
                {
                    Id = "p03",
                    Name = "name 3",
                    Price = 8,
                    Photo = "thumb3.gif"
                }
            };
        }

        public List<Product> findAll()
        {
            return Products;
        }

        public Product find(string id)
        {
            return Products.Where(p => p.Id == id).FirstOrDefault();
        }

    }
}




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

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace LearnASPNETCoreRazorPagesWithRealApps.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 Pages. In this folder, create new Razor Page named Index as below:

using System.Collections.Generic;
using LearnASPNETCoreRazorPagesWithRealApps.Entities;
using LearnASPNETCoreRazorPagesWithRealApps.Models;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class IndexModel : PageModel
    {
        public List<Product> Products;

        public void OnGet()
        {
            ProductModel productModel = new ProductModel();
            Products = productModel.findAll();
        }
    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel

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

    <h3>Product List</h3>
    <table border="1">
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Photo</th>
            <th>Price</th>
            <th>Action</th>
        </tr>
        @foreach (var product in Model.Products)
        {
            <tr align="center">
                <td>@product.Id</td>
                <td>@product.Name</td>
                <td><img src="~/images/@product.Photo" width="120" height="100" /></td>
                <td>$@product.Price</td>
                <td>
                    <a asp-page="cart" asp-page-handler="buynow" asp-route-id="@product.Id">Buy Now</a>
                </td>
            </tr>
        }
    </table>

</body>
</html>




In Pages folder, create new Razor Page named Cart as below:

using System.Collections.Generic;
using LearnASPNETCoreRazorPagesWithRealApps.Entities;
using LearnASPNETCoreRazorPagesWithRealApps.Helpers;
using LearnASPNETCoreRazorPagesWithRealApps.Models;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class CartModel : PageModel
    {
        public List<Item> cart { get; set; }
        public double Total { get; set; }

        public void OnGet()
        {
            cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            Total = cart.Sum(i => i.Product.Price * i.Quantity);
        }

        public IActionResult OnGetBuyNow(string id)
        {
            var productModel = new ProductModel();
            cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            if (cart == null)
            {
                cart = new List<Item>();
                cart.Add(new Item
                {
                    Product = productModel.find(id),
                    Quantity = 1
                });
                SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            }
            else
            {
                int index = Exists(cart, id);
                if (index == -1)
                {
                    cart.Add(new Item
                    {
                        Product = productModel.find(id),
                        Quantity = 1
                    });
                }
                else
                {
                    cart[index].Quantity++;
                }
                SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            }
            return RedirectToPage("Cart");
        }

        public IActionResult OnGetDelete(string id)
        {
            cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            int index = Exists(cart, id);
            cart.RemoveAt(index);
            SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            return RedirectToPage("Cart");
        }

        public IActionResult OnPostUpdate(int[] quantities)
        {
            cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            for (var i = 0; i < cart.Count; i++)
            {
                cart[i].Quantity = quantities[i];
            }
            SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            return RedirectToPage("Cart");
        }

        private int Exists(List<Item> cart, string id)
        {
            for (var i = 0; i < cart.Count; i++)
            {
                if (cart[i].Product.Id == id)
                {
                    return i;
                }
            }
            return -1;
        }

    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.CartModel
@{
    Layout = null;
}

<!DOCTYPE html>

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

    <h3>Cart</h3>
    <form method="post" asp-page="cart" asp-page-handler="update">
        <table border="1">
            <tr>
                <th>Action</th>
                <th>Id</th>
                <th>Name</th>
                <th>Photo</th>
                <th>Price</th>
                <th>Quantity <input type="submit" value="Update" /></th>
                <th>Sub Total</th>
            </tr>
            @foreach (var item in Model.cart)
            {
                <tr align="center">
                    <td align="center">
                        <a asp-page="cart" asp-page-handler="delete" asp-route-id="@item.Product.Id">X</a>
                    </td>
                    <td>@item.Product.Id</td>
                    <td>@item.Product.Name</td>
                    <td><img src="~/images/@item.Product.Photo" width="120" height="100" /></td>
                    <td>$@item.Product.Price</td>
                    <td><input type="number" name="quantities" value="@item.Quantity" min="1" style="width: 50px;" /></td>
                    <td>
                        $@(item.Product.Price * item.Quantity)
                    </td>
                </tr>
            }
            <tr>
                <td colspan="6" align="right">Total</td>
                <td align="center">$@Model.Total</td>
            </tr>
        </table>
    </form>
    <a asp-page="index">Continue Shopping</a>

</body>
</html>




Open Index Razor Page with following url: http://localhost:1115

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