From 234b72e4d09760aefad231aeb3e452c33606feb6 Mon Sep 17 00:00:00 2001 From: Bhrugen Patel Date: Mon, 27 Sep 2021 14:46:11 -0500 Subject: [PATCH] Section 12 - View Component Code --- .../ShoppingCartViewComponent.cs | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 BulkyBookWeb/ViewComponents/ShoppingCartViewComponent.cs diff --git a/BulkyBookWeb/ViewComponents/ShoppingCartViewComponent.cs b/BulkyBookWeb/ViewComponents/ShoppingCartViewComponent.cs new file mode 100644 index 0000000..b27634f --- /dev/null +++ b/BulkyBookWeb/ViewComponents/ShoppingCartViewComponent.cs @@ -0,0 +1,43 @@ +using BulkyBook.DataAccess.Repository.IRepository; +using BulkyBook.Utility; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; + +namespace BulkyBookWeb.ViewComponents +{ + public class ShoppingCartViewComponent : ViewComponent + { + private readonly IUnitOfWork _unitOfWork; + public ShoppingCartViewComponent(IUnitOfWork unitOfWork) + { + _unitOfWork= unitOfWork; + } + + public async Task InvokeAsync() + { + var claimsIdentity = (ClaimsIdentity)User.Identity; + var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier); + if (claim != null) + { + if (HttpContext.Session.GetInt32(SD.SessionCart) != null) + { + return View(HttpContext.Session.GetInt32(SD.SessionCart)); + } + else + { + HttpContext.Session.SetInt32(SD.SessionCart, + _unitOfWork.ShoppingCart.GetAll(u => u.ApplicationUserId == claim.Value).ToList().Count); + return View(HttpContext.Session.GetInt32(SD.SessionCart)); + } + } + else + { + HttpContext.Session.Clear(); + return View(0); + } + } + } +}