第8章 SportsStorePeta 领航

第8章 SportsStorePeta 导航

一、添加导航控制

  1.过滤产品列表 

    增强ProductsListViewModel

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

    修改List动作方法    

 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.调整URL方案(修改路由)

            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}");

    修改分布链接添加分页信息    

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

  3.建立分类导航菜单

    子动作:适用于创建诸如可重用导航控件之类的东西。依赖于“RenderAction”辅助器方法,在当前视图中包含一个任意动作方法的输出。

    (1)创建导航控制器

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";
        }

    }
}

    修改布局:

  RenderAction方法会将它的内容直接写入到响应流,必须把这个调用封装在一个Razor代码块中,而且以分号为语句结束。@{Html.RenderAction("Menu","Nav");}

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

    (2)生成分类列表

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)创建分部视图 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

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;
}

    高亮当前分类  

 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.修正页面计数

  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);
        }

二、建立购物车

  1.定义购物车实体

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.添加按钮“加入购物车”

@model SportsStorePeta.WebUI.Models.ProductViewModel

<div class="item">
    <h3>@Model.Name</h3>
    @Model.Description
    @using (Html.BeginForm("AddToCart", "Cart"))
    {
        @Html.HiddenFor(x=>x.ProductId)
        @Html.Hidden("returnUrl",Request.Url.PathAndQuery)
        <input type="submit" value="加入购物车"/>
    }
    <h4>@Model.Price</h4>
</div>

    在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.实现购物车控制器

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.显示购物车内容

    添加CartIndexViewModel视图模型类

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; }
    }
}

  CartController中添加Index动作方法:

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

  添加Index视图:

@model SportsStorePeta.WebUI.Models.CartIndexViewModel

@{
    ViewBag.Title = "我的购物车";
}
<h2>我的购物车</h2>
<table width="90%" align="center">
    <thead>
    <tr>
        <th align="left">物品</th>
        <th align="center">数量</th>
        <th align="right">单价</th>
        <th align="right">金额</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>
        </tr>
    }
    </tbody>
    <tfoot>
    <tr>
        <td colspan="3" align="right">合计</td>
        <td align="right">@Model.Cart.ComputeTotalValue().ToString("c")</td>
    </tr>
    </tfoot>
</table>

<p align="center" class="actionButtons">
    <a href="@Model.ReturnUrl">继续购物</a>
</p>

  Css样式:

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;
}

源码:http://yunpan.cn/cdg5yKnzmH3dF 访问密码 7d00