MVC project practice, under the three-tier architecture to achieve SportsStore-06, to achieve shopping cart

Source: Internet
Author: User

SportsStore is a master of ASP. the MVC project demonstrated in NET MVC3 framework (Third edition) covers many aspects of MVC, including: use DI container, URL optimization, navigation, paging, shopping cart, order, product management, Image Upload ...... it is a good MVC practice project, but it is not developed under a multi-layer framework, and there is still a distance from the real project. This series will try to implement the SportsStore project in a multi-layer framework and implement some functions in its own way.

 

This is the sixth article in the series, including:

■ 8. Shopping Cart
□8.1 shopping cart model shopping cart help class
□8.2 add the "add to shopping cart" button
□8.3 Add "Remove" button to display the content of the shopping cart
□8.4 display shopping cart Summary

8. Shopping Cart

8.1 shopping cart model shopping cart help class

Logically, the shopping cart help class not only processes products, but also the quantity of each Product. We combine these two factors into a basic unit:

public class CartLine    {        public Product Product { get; set; }        public int Quantity { get; set; }    }

The main work of the shopping cart help class is to deal with this CartLine set: adding, removing, calculating the total price, clearing, etc.

Using System. collections. generic; using System. linq; using MySportsStore. model; namespace MySportsStore. webUI. models {public class Cart {private List <CartLine> lineCollection = new List <CartLine> (); // Add public void AddItem (Product product, int quantity) {CartLine = lineCollection. where (p => p. product. id = product. id ). firstOrDefault (); if (line = null) {lineCollection. add (new CartLine () {Product = product, Quantity = quantity});} else {line. quantity + = quantity ;}// remove public void RemoveLine (Product product) {lineCollection. removeAll (p => p. product. id = product. id);} // calculates the total price of public decimal ComputeTotalValue () {return lineCollection. sum (p => p. product. price * p. quantity);} // Clear public void Clear () {lineCollection. clear () ;}// get public IEnumerable <CartLine> Lines {get {return lineCollection ;}}}}

 

8.2 add the "add to shopping cart" button

Add the "add to shopping cart" button in the partial view of the product to pass the Produect Id and the URL of the current page as a hidden domain to the Controller method:

@ Model MySportsStore. model. product <div class = "item"> 

In the Cart Controller method to be created, the Cart instance must be used, and the instance runs between pages, so it should be stored in the Session. First, you can obtain an instance of the Cart class in the following ways:

private Cart GetCart()        {            Cart cart = (Cart)Session["Cart"];            if (cart == null)            {                cart = new Cart();                Session["Cart"] = cart;            }            return cart;        }

You can also customize a ModelBinder to get the Cart class instance from the Session:

using System.Web.Mvc;using MySportsStore.WebUI.Models;namespace MySportsStore.WebUI.Extension{    public class CartModelBinder : IModelBinder    {        private const string sessionKey = "Cart";        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)        {            Cart cart = (Cart)controllerContext.HttpContext.Session[sessionKey];            if (cart == null)            {                cart = new Cart();                controllerContext.HttpContext.Session[sessionKey] = cart;            }            return cart;        }    }}

Register the custom ModelBinder to MVC in the Global. asax Global file:

protected void Application_Start()        {            ......            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());            ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder());        }

With the above preparations, there can be a Cart type parameter in the Cart controller's method parameter. This parameter value is obtained directly from the custom CartModelBinder:

Using System. linq; using System. web. mvc; using MySportsStore. IBLL; using MySportsStore. model; using MySportsStore. webUI. models; using Ninject; namespace MySportsStore. webUI. controllers {public class CartController: BaseController {[Inject] public IProductService ProductService {get; set;} public CartController () {this. addDisposableObject (ProductService);} public ActionResult Index (Cart cart, string ReturnUrl) {return View (new CartIndexViewModel {// Cart = GetCart (), Cart = cart, ReturnUrl = returnUrl});} // Add it to the Cart public RedirectToRouteResult AddToCart (cart Cart, int Id, string returnUrl) {Product product = ProductService. loadEntities (p => p. id = Id ). firstOrDefault (); if (product! = Null) {// GetCart (). addItem (product, 1); cart. addItem (product, 1);} return RedirectToAction ("Index", new {returnUrl});} // remove public RedirectToRouteResult RemoveFromCart (Cart cart, int Id, string returnUrl) from the shopping Cart) {Product product = ProductService. loadEntities (p => p. id = Id ). firstOrDefault (); if (product! = Null) {// GetCart (). removeLine (product); cart. removeLine (product);} return RedirectToAction ("Index", new {returnUrl});} public ViewResult Summary (Cart cart) {return View (cart);} private Cart GetCart () {Cart cart = (Cart) Session ["Cart"]; if (cart = null) {cart = new Cart (); Session ["Cart"] = cart ;} return cart ;}}}

Run:

 

Show the "Remove" button for the content of the shopping cart

In addition to presenting the content of the shopping cart, you must have an attribute in the view model corresponding to the view page to store the previous URL, click "continue shopping" to go back to the previous page.


The View Model on the Content View page of the shopping cart is:

namespace MySportsStore.WebUI.Models{    public class CartIndexViewModel    {        public Cart Cart { get; set; }        public string ReturnUrl { get; set; }    }}

Cart/Index. cshtml View:

@ Model MySportsStore. WebUI. Models. CartIndexViewModel @ {ViewBag. Title = "Index"; Layout = "~ /Views/Shared/_ Layout. cshtml ";} <table width = "50%" align = "left"> <thead> <tr> <th align = "left"> product name </th> <th align = "center"> quantity </th> <th align = "right"> unit price </th> <th align = "right"> subtotal </th> </tr> </thead> <tbody> @ foreach (var line in Model. cart. lines) {<tr> <td align = "left"> @ line. product. name </td> <td align = "center"> @ line. quantity </td> <td align = "right"> @ line. product. price. toString ("c") </td> <td align = "right"> @ (line. quantity * line. product. price ). toString ("c") </td> <td> @ using (Html. beginForm ("RemoveFromCart", "Cart") {@ Html. hidden ("Id", line. product. id) @ Html. hiddenFor (x => x. returnUrl) <input class = "actionButtons" type = "submit" value = "Remove"/>}</td> </tr >}</tbody> <tfoot> <tr> <td colspan = "3" align = "right"> total: </td> <td align = "right"> @ Model. cart. computeTotalValue (). toString ("c") </td> </tr> </tfoot> </table> <p align = "left" class = "actionButtons" style = "width: 100%; clear: both "> <a href =" @ Model. returnUrl "> continue shopping </a> </p>

Run:

 

8.4 display shopping cart Summary

A shopping cart abstract is usually placed in the public part of the page to show how many items you have bought and how much you have spent, and provide a link pointing to the display page of the shopping cart, which exists in the form of partial views:

@ Model MySportsStore. webUI. models. cart @ {Layout = null;} <div id = "cart"> <span class = "caption"> <B> shopping Cart details: </B> @ Model. lines. sum (x => x. quantity), @ Model. computeTotalValue (). toString ("c") </span> @ Html. actionLink ("Settlement", "Index", "Cart", new {returnUrl = Request. url. pathAndQuery}, null) </div>

Put this part of the view in the public part of the page, that is, Views/Shared/_ Layout. cshtml:

<! DOCTYPE html> 

Run:

Now, the shopping cart function is complete.

 

The series "MVC project practices, implementing SportsStore in a three-tier architecture" includes:

MVC project practice, under the three-tier architecture to achieve SportsStore-01, EF Code First modeling, DAL layer MVC project practice, under the three-tier architecture to achieve SportsStore-02, DbSession layer, BLL layer MVC project practice, in the three-tier architecture to achieve SportsStore-03, Ninject controller factory MVC project practice, in the three-tier architecture to achieve SportsStore-04, achieve paging MVC project practice, in the three-tier architecture to achieve SportsStore-05, implement the MVC project practice of navigation, implement SportsStore-06 under the three-tier architecture, and implement shopping cart

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.