希望实现的效果是:对购物车中所有商品的总价,实现9折或8折:

当点击"9折":

当点击"8折":

□ 思路

8折或9折是打折接口的不同实现,关键是:由什么条件决定使用哪种打折方式?

--当点击8折或9折链接的时候,把参数放在路由中,然后在自定义控制器工厂中根据参数的不同选择使用哪种打折方式。

□ model

public class CartLine
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int Quantity { get; set; }
    }

□ 接口

using MvcApplication2.Models;

namespace MvcApplication2
{
    public interface IDiscount
    {
        decimal GetFinalPrice(List<CartLine> cartLines);
    }
}

□ 接口的2种实现

using System.Collections.Generic;
 
namespace MvcApplication2.implementation
{
    public class NineDiscount : IDiscount
    {
        public decimal GetFinalPrice(List<Models.CartLine> cartLines)
        {
            decimal result = 0.0M;
            foreach (var item in cartLines)
            {
                result += item.Price*item.Quantity;
            }
            return result*(90M/100M);
        }
    }
}
 
 
 
using System.Collections.Generic;
 
namespace MvcApplication2.implementation
{
    public class EightDiscount : IDiscount
    {
        public decimal GetFinalPrice(List<Models.CartLine> cartLines)
        {
            decimal result = 0.0M;
            foreach (var item in cartLines)
            {
                result += item.Price * item.Quantity;
            }
            return result * (80M / 100M);
        }
    }
}
 

□ HomeController

using System.Collections.Generic;
using System.Web.Mvc;
using MvcApplication2.Models;
 
namespace MvcApplication2.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            List<CartLine> cartLines = new List<CartLine>()
            {
                new CartLine(){Id = 1, Name = "Product1", Price = 80M, Quantity = 2},
                new CartLine(){Id = 2, Name = "Product2", Price = 100M, Quantity = 3},
            };
            Session["cart"] = cartLines;
            return View(cartLines);
        }
 
    }
}
 

□ Home/Index.cshtml

把不同的打折方式放在路由中传递。

@model List<MvcApplication2.Models.CartLine>
 
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<h2>Index</h2>
 
<table>
    <tr style="background-color: #e3e3e3;">
        <td>产品</td>
        <td>价格</td>
        <td>数量</td>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.Name</td>
            <td>@string.Format("{0:C}", item.Price)</td>
            <td>@item.Quantity</td>
        </tr>
    }
</table>
 
<p>
    @Html.ActionLink("9折购买", "Index", "Shop", new {policy = "Nine"},new {})
</p>
 
<p>
    @Html.ActionLink("8折购买", "Index", "Shop", new {policy = "Eight"},new {})
</p>    
 

□ 自定义控制器工厂,使用Ninject,根据路由参数policy的不同,决定选择具体的打折接口实现

using System;
using System.Web.Mvc;
using System.Web.Routing;
using MvcApplication2.implementation;
using Ninject;
 
namespace MvcApplication2.Extension
{
    public class NinjectControllerFactory : DefaultControllerFactory
    {
        IKernel ninjectKernel;
        string policy = "";
 
        public NinjectControllerFactory()
        {
            ninjectKernel = new StandardKernel();
        }
 
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (requestContext.RouteData.Values["policy"] != null)
            {
                policy = requestContext.RouteData.Values["policy"].ToString();
            }
            AddBindings();
            return controllerType == null ? null : (IController) ninjectKernel.Get(controllerType);
        }
 
        private void AddBindings()
        {
            switch (policy)
            {
                case "Eight":
                    ninjectKernel.Rebind<IDiscount>().To<EightDiscount>();
                    break;
                case "Nine":
                    ninjectKernel.Rebind<IDiscount>().To<NineDiscount>();
                    break;
                default:
                    ninjectKernel.Rebind<IDiscount>().To<NineDiscount>();
                    break;
            }
        }
    }
}
 

□ 自定义控制器工厂全局注册

ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

□ ShopController中使用打折接口方法

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using MvcApplication2.Models;
 
 
namespace MvcApplication2.Controllers
{
    public class ShopController : Controller
    {
        public IDiscount _Discount;
 
        public ShopController(IDiscount discount)
        {
            this._Discount = discount;
        }
 
        public ActionResult Index(string policy)
        {
            List<CartLine> cartLines = new List<CartLine>();
            if (Session["cart"] != null)
            {
                cartLines = (List<CartLine>)Session["cart"];
            }
            ViewData["total"] = String.Format("{0:C}",_Discount.GetFinalPrice(cartLines));
            return View();
        }
 
    }
}
 

□ Shop/Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
打折后的价格为: @ViewData["total"]

□ 自定义路由

为了让url更直观,符合controller/action/paramter:

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{policy}",
                defaults: new { controller = "Home", action = "Index", policy = UrlParameter.Optional }
            );

MVC扩展控制器工厂,通过继承DefaultControllerFactory来决定使用哪个接口实现,使用Ninject的更多相关文章

  1. MVC扩展控制器工厂,通过实现IControllerFactory,根据action名称生成不同的Controller

    关于控制器工厂的扩展,要么通过实现IControllerFactory接口,要么通过继承DefaultControllerFactory.本篇中,我想体验的是: 1.当请求经过路由,controlle ...

  2. MVC扩展控制器, 把部分视图转换成字符串(带验证信息), 并以json传递给前端视图

    当我们使用jQuery异步提交表单数据的时候,需要把部分视图转换成字符串(带验证信息),以json的形式传递给前端视图.   使用jQuery异步加载部分视图,返回内容追加到页面某个div:   jQ ...

  3. MVC项目实践,在三层架构下实现SportsStore-03,Ninject控制器工厂等

    SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管 ...

  4. .NET/ASP.NET MVC Controller 控制器(IController控制器的创建过程)

    阅读目录: 1.开篇介绍 2.ASP.NETMVC IControllerFactory 控制器工厂接口 3.ASP.NETMVC DefaultControllerFactory 默认控制器工厂 4 ...

  5. .NET/ASP.NET MVC Controller 控制器(深入解析控制器运行原理)

    阅读目录: 1.开篇介绍 2.ASP.NETMVC Controller 控制器的入口(Controller的执行流程) 3.ASP.NETMVC Controller 控制器的入口(Controll ...

  6. 三、ASP.NET MVC Controller 控制器(二:IController控制器的创建过程)

    阅读目录: 1.开篇介绍 2.ASP.NETMVC IControllerFactory 控制器工厂接口 3.ASP.NETMVC DefaultControllerFactory 默认控制器工厂 4 ...

  7. 二、ASP.NET MVC Controller 控制器(一:深入解析控制器运行原理)

    阅读目录: 1.开篇介绍 2.ASP.NETMVC Controller 控制器的入口(Controller的执行流程) 3.ASP.NETMVC Controller 控制器的入口(Controll ...

  8. NET/ASP.NET MVC Controller 控制器(一:深入解析控制器运行原理)

    阅读目录: 1.开篇介绍 2.ASP.NETMVC Controller 控制器的入口(Controller的执行流程) 3.ASP.NETMVC Controller 控制器的入口(Controll ...

  9. ASP.NET MVC 创建控制器类过程

    MvcHandler.ProcessRequestInit()方法: 1.1获取控制器的名称string requiredString = this.RequestContext.RouteData. ...

随机推荐

  1. python图片处理(二)

    python中图像处理有pillow和skimage 图像中一般有个RGBA值,RGB顾名思义就是红绿蓝值,A表示alpha表示是透明度. from PIL import ImageColor pri ...

  2. MySQL 5.1完全卸载

    第一步:控制面板里的增加删除程序内进行删除 第二步:删除MySQL文件夹下的my.ini文件,如果备份好,可以直接将文件夹全部删除 第三步:regedit进入注册表 HKEY_LOCAL_MACHIN ...

  3. 解决insert语句插入时,需要写列值的问题

    今天发现解决这个问题其实很简单,闲话不多谈,我直接附上语句 ) select @s = isnull(@s+',', '') + [name] from syscolumns where id = o ...

  4. PowerMock+SpringMVC整合并测试Controller层方法

    PowerMock扩展自Mockito,实现了Mockito不支持的模拟形式的单元测试.PowerMock实现了对静态方法.构造函数.私有方法以及final方法的模拟支持,对静态初始化过程的移除等强大 ...

  5. Oracle约束

    1.非空约束 DROP TABLE member PURGE; CREATE TABLE member( mid NUMBER, name ) NOT NULL ); 2.唯一约束 DROP TABL ...

  6. 选择性卸载eclipse安装过的工具

    我们有时候需要卸载eclipse中之前安装的一些工具,而不想全部删除,那就可以采取下面的方式: 打开eclipse,Help->About Eclipse->Installation De ...

  7. Asp.net Vnext 自定义日志

    概述 本文已经同步到<Asp.net Vnext 系列教程 >中] 可以通过自定义日志,把错误消息记录到数据库 实现 在启动文件Startup Configure方法中加入自定义的日志提供 ...

  8. 配置tomcat报错: Unknown version of Tomcat was specified.

    报错原因:路劲没选择对,应选择bin文件夹的上一层目录,也不能选择bin目录

  9. MySQL性能优化(七·下)-- 锁机制 之 行锁

    一.行锁概念及特点 1.概念:给单独的一行记录加锁,主要应用于innodb表存储引擎 2.特点:在innodb存储引擎中应用比较多,支持事务.开销大.加锁慢:会出现死锁:锁的粒度小,并发情况下,产生锁 ...

  10. Request常用方法(转)

    原文地址:http://www.lihuai.net/program/python/1617.html Python Requests库:HTTP for Humans 时间: 2014/12/30 ...