Chapter 6 SportsStorePeta navigation, miracle warmth Chapter 6 68

Source: Internet
Author: User
Tags actionlink

Chapter 6 SportsStorePeta navigation, miracle warmth Chapter 6 68

1. Add Navigation Control

1. filter the product list

Enhance ProductsListViewModel

 public class ProductsListViewModel    {        public IEnumerable<ProductViewModel> Products { get; set; }        public PageInfo PagingInfo { get; set; }        public string CurrentCategory { get; set; }    }

Modify the List action Method

 public ViewResult List(string category,int page=1)        {            ProductsListViewModel model = new ProductsListViewModel            {                Products = GetProductViewModelListByProducts( _repository.Products.Where(p=>category==null||p.Category==category).OrderBy(p => p.ProductId).Skip((page - 1)*PageSize).Take(PageSize)),                PagingInfo = new PageInfo { CurrentPage = page,ItemsPerPage = PageSize,TotalItems = _repository.Products.Count()} ,                CurrentCategory = category                            };            return View(model);        } 

2. Adjust the URL scheme (modify the route)

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");            routes.MapRoute(null, "", new {controller = "Product", action = "List", category = (string) null, page = 1});            routes.MapRoute(null, "Page{page}", new { controller = "Product", action = "List", category = (string)null},new{page=@"\d+"});            routes.MapRoute(null, "{category}", new { controller = "Product", action = "List", page = 1 });            routes.MapRoute(null, "{category}/Page{page}", new { controller = "Product", action = "List" },new{page=@"\d+"});            routes.MapRoute(null, "{controller}/{action}");

Modify the distribution link and add paging information

<div class="pager">    @Html.PageLinks(Model.PagingInfo,x=>Url.Action("List",new{page=x,category=Model.CurrentCategory}))</div>

3. Create a category navigation menu

    Sub-action: Applicable to the creation of reusable navigation controls. Depending on the "RenderAction" helper method, the current view contains the output of any action method.

(1) create a navigation Controller

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace SportsStorePeta.WebUI.Controllers{    public class NavController : Controller    {        //        // GET: /Nav/        public string Menu()        {            return "Hello from NavController";        }    }}

Modify layout:

The RenderAction method will directly write its content to the response stream. You must encapsulate this call inRazor code blockAnd end with a semicolon. @ {Html. RenderAction ("Menu", "Nav ");}

<div id="categories">   @{       Html.RenderAction("Menu","Nav");   }</div>

(2) generate a category list

using System;using System.Collections.Generic;using System.Data.Entity.Infrastructure;using System.Linq;using System.Web;using System.Web.Mvc;using SportsStorePeta.Domain.Abstract;namespace SportsStorePeta.WebUI.Controllers{    public class NavController : Controller    {        private readonly IProductRepository _repository;        public NavController(IProductRepository repo)        {            _repository = repo;        }          public PartialViewResult Menu()        {            IEnumerable<string> categories = _repository.Products.Select(x => x.Category).Distinct().OrderBy(x => x);            return PartialView(categories);        }    }}

(3) create a Menu

@model IEnumerable<string>@Html.ActionLink("Home","List","Product")@foreach (var link in Model){    @Html.RouteLink(link,new{controller="Product",action="List",category=link,page=1})}

CSS used for classification links

div#categories a {    font: bold 1.1em "Arial Narrow", "Franklin Gothic medium", Arial;display: block;    text-decoration: none;padding: .6em;color: black;    border-bottom: 1px solid silver;}div#categories a.selected {    background-color: #666;color: white;}

Highlight current category

 public PartialViewResult Menu(string category=null)        {            ViewBag.SelectedCategory = category;            IEnumerable<string> categories = _repository.Products.Select(x => x.Category).Distinct().OrderBy(x => x);            return PartialView(categories);        }
@model IEnumerable<string>@Html.ActionLink("Home","List","Product")@foreach (var link in Model){    @Html.RouteLink(link, new { controller = "Product", action = "List", category = link, page = 1 },    new { @class=link==ViewBag.SelectedCategory?"selected":null}    )}

4. corrected page count

  public ProductController(IProductRepository productRepository)        {            _repository = productRepository;        }        public ViewResult List(string category,int page=1)        {            ProductsListViewModel model = new ProductsListViewModel            {                Products = GetProductViewModelListByProducts( _repository.Products.Where(p=>category==null||p.Category==category).OrderBy(p => p.ProductId).Skip((page - 1)*PageSize).Take(PageSize)),                PagingInfo = new PageInfo { CurrentPage = page,ItemsPerPage = PageSize,TotalItems =category==null?_repository.Products.Count():_repository.Products.Count(e => e.Category==category)} ,                CurrentCategory = category                };            return View(model);        }

2. Create a shopping cart

1. Define the shopping cart entity

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace SportsStorePeta.Domain.Entities{   public class Cart   {       private List<CartLine> lineCollection = new List<CartLine>();       public void AddItem(Product product, int quantity)       {           CartLine line = lineCollection.FirstOrDefault(p => p.Product.ProductId == product.ProductId);           if (line == null)           {               lineCollection.Add(new CartLine{Product = product,Quantity = quantity});           }           else           {               line.Quantity += quantity;           }       }       public void RemoveLine(Product product)       {           lineCollection.RemoveAll(l => l.Product.ProductId == product.ProductId);       }       public decimal ComputeTotalValue()       {           return lineCollection.Sum(e => e.Product.Price*e.Quantity);       }       public void Clear()       {           lineCollection.Clear();       }       public IEnumerable<CartLine> Lines{get { return lineCollection; }}    }   public class CartLine   {       public Product Product { get; set; }       public int Quantity { get; set; }   }}

2. Add the button "add to shopping cart"

@ Model SportsStorePeta. WebUI. Models. ProductViewModel <div class = "item"> @ Using (Html. beginForm ("AddToCart", "Cart") {@ Html. hiddenFor (x => x. productId) @ Html. hidden ("returnUrl", Request. url. pathAndQuery)<Input type = "submit" value = "add to shopping cart"/>}<H4> @ Model. Price 

Set button styles in site.css

form {    margin: 0;padding: 0;}div.item form{ float: right;}div.item input {    color: white;background: #333;border: 1px solid black;cursor: pointer;}

3. Implement the shopping cart Controller

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using SportsStorePeta.Domain.Abstract;using SportsStorePeta.Domain.Entities;namespace SportsStorePeta.WebUI.Controllers{    public class CartController : Controller    {        private IProductRepository _repository;        public CartController(IProductRepository repo)        {            _repository = repo;        }        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;        }    }}

4. display the content of the shopping cart

Add CartIndexViewModel view model class

using System;using System.Collections.Generic;using System.Linq;using System.Web;using SportsStorePeta.Domain.Entities;namespace SportsStorePeta.WebUI.Models{    public class CartIndexViewModel    {        public Cart Cart { get; set; }        public string ReturnUrl { get; set; }    }}

Add the Index Action Method to CartController:

      public ViewResult Index(string returnUrl)        {            return View(new CartIndexViewModel {Cart = GetCart(), ReturnUrl = returnUrl});        }

Add the Index View:

@ Model SportsStorePeta. webUI. models. cartIndexViewModel @ {ViewBag. title = "my shopping cart ";} 

Css style:

h2{margin-top: 0.3em}tfoot td {    border-top: 1px dotted gray;font-weight: bold;}.actionButtons a,input.actionButtons {    font: .8em Arial;color: white;margin: .5em;    text-decoration: none;padding: .15em 1.5em .2em 1.5em;    background-color: #353535;border: 1px solid black;}

Source code: http://yunpan.cn/cdg5yKnzmH3dF access password 7d00

Related Article

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.