8.2.3 Implementing the Cart Controller; Listing 8-14 The Contents of the CartController.cs File

chap08
Jason Zhu 2021-09-13 00:23:59 +10:00
parent 905ecd6969
commit a24fe02bbd
2 changed files with 58 additions and 0 deletions

View File

@ -0,0 +1,56 @@
using SportsStore.Domain.Abstract;
using SportsStore.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SportsStore.WebUI.Controllers
{
public class CartController : Controller
{
private IProductRepository repository;
public CartController(IProductRepository repo)
{
repository = repo;
}
// GET: Cart
public RedirectToRouteResult AddToCart(int productId, string returnUrl)
{
Product product = repository.Products
.FirstOrDefault(p => p.ProductID == productId);
if (product != null)
{
GetCart().AddItem(product, 1);
}
return RedirectToAction("Index", new { returnUrl });
}
public RedirectToRouteResult RemoveFromCart(int productId, string returnUrl)
{
Product product = repository.Products
.FirstOrDefault(p => p.ProductID == productId);
if (product != null)
{
GetCart().RemoveLine(product);
}
return RedirectToAction("Index", new { returnUrl });
}
private Cart GetCart()
{
Cart cart = (Cart)Session["Cart"];
if (cart == null)
{
cart = new Cart();
Session["Cart"] = cart;
}
return cart;
}
}
}

View File

@ -130,6 +130,7 @@
<ItemGroup> <ItemGroup>
<Compile Include="App_Start\NinjectWebCommon.cs" /> <Compile Include="App_Start\NinjectWebCommon.cs" />
<Compile Include="App_Start\RouteConfig.cs" /> <Compile Include="App_Start\RouteConfig.cs" />
<Compile Include="Controllers\CartController.cs" />
<Compile Include="Controllers\NavController.cs" /> <Compile Include="Controllers\NavController.cs" />
<Compile Include="Controllers\ProductController.cs" /> <Compile Include="Controllers\ProductController.cs" />
<Compile Include="Global.asax.cs"> <Compile Include="Global.asax.cs">
@ -159,6 +160,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="App_Data\" /> <Folder Include="App_Data\" />
<Folder Include="Views\Cart\" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SportsStore.Domain\SportsStore.Domain.csproj"> <ProjectReference Include="..\SportsStore.Domain\SportsStore.Domain.csproj">