ASP.NET + MVC5 入门完整教程七
https://blog.csdn.net/qq_21419015/article/details/80474956
这里主要介绍三类工具之一的 依赖项注入(DI)容器,其他两类 单元测试框架和仿照工具以后介绍。
从创建一个简单的示例开始,名称为"EssentialTools" ,使用MVC空模板,如下所示:
在 Models 文件夹中添加一个名为 Products.cs 的类,添加内容如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EssentialTools.Models
{
public class Product
{
public int ProductId { get; set; }
public string Name { set; get; }
public string Description { get; set; }
public decimal Price { set; get; }
public string Category { get; set; }
}
}
再添加一个类,计算Product东西调集总价,名称为 LinqValueCalculator.cs ,添加内容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EssentialTools.Models
{
public class LinqValueCalculator
{
public decimal ValueProducts(IEnumerable<Product> products)
{
return products.Sum(p => p.Price);
}
}
}
LinqValueCalculator 类界说了一个单一的要领ValueProducts;他使用了LINQ的Sum要领将通报给该要领的可枚举东西中每一个Product东西的Price 属性值在一起
最后一个模型类称为 ShoppingCart ,暗示 Product东西调集,并且使用LinqValueCalculator 来确定总价。添加内容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EssentialTools.Models
{
public class ShoppingCart
{
private LinqValueCalculator calc;
public ShoppingCart(LinqValueCalculator calcParam)
{
calc = calcParam;
}
public IEnumerable<Product> Products{ get; set; }
public decimal CalculateProductToal()
{
return calc.ValueProducts(Products) ;
}
}
}
在 Controllers 文件夹下添加一个名称为 “HomeController”的新控制器,设置内容如下,Index 行动要领创建了一个“Product”东西数组,并使用 LinqValueCalculator 东西孕育产生的值,将其通报给View要领。如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EssentialTools.Models;
namespace EssentialTools.Controllers
{
public class HomeController : Controller
{
// GET: Home
private Product[] products =
{
new Product {Name = "Kayak",Description = "Watersports",Category = "Watersport",Price = 122M },
new Product {Name = "Lifejacket",Description = "Watersports",Category = "Watersports",Price = 162M },
new Product {Name = "Soccer ball",Description = "Soccer",Category = "Soccer",Price = 172.25M },
new Product {Name = "Corner flag",Description = "Soccer",Category = "Soccer",Price = 82.15M }
};
public ActionResult Index()
{
LinqValueCalculator lvc = new LinqValueCalculator();
ShoppingCart sc = new ShoppingCart(lvc){ Products = products }; // public IEnumerable<Product> Products
decimal totalValue = sc.CalculateProductToal();
return View(totalValue);
}
}
}
最后给项目添加视图,选中Index 右键添加视图,设置内容如下所示:
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30814.html