9.1.1 Creating a Custom Model Binder; Listing 9-1. The Contents of the CartModelBinder.cs File

This commit is contained in:
Jason Zhu 2021-09-18 22:26:21 +10:00
parent 8dff8292b3
commit 1bb96ab788
2 changed files with 35 additions and 0 deletions

View File

@ -0,0 +1,34 @@
using System.Web.Mvc;
using SportsStore.Domain.Entities;
namespace SportsStore.WebUI.Infrastructure.Binders
{
public class CartModelBinder : IModelBinder
{
private const string sessionKey = "Cart";
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
// get the Cart from the session
Cart cart = null;
if (controllerContext.HttpContext.Session != null)
{
cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
}
// create the Cart if there wasn't one in the session data
if (cart == null)
{
cart = new Cart();
if (controllerContext.HttpContext.Session != null)
{
controllerContext.HttpContext.Session[sessionKey] = cart;
}
}
// return the cart
return cart;
}
}
}

View File

@ -137,6 +137,7 @@
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="HtmlHelpers\PagingHelpers.cs" />
<Compile Include="Infrastructure\Binders\CartModelBinder.cs" />
<Compile Include="Infrastructure\NinjectDependencyResolver.cs" />
<Compile Include="Models\CartIndexViewModel.cs" />
<Compile Include="Models\PagingInfo.cs" />