结构如下: 1、在Models 层文件夹里面,创建商品类Product public class Product { public int ProductID { get ; set ; } public string ProductName { get ; set ; } public double ProductPrice { get ; set ; } public string ProductDe
结构如下:
1、在Models 层文件夹里面,创建商品类Product
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public double ProductPrice { get; set; }
public string ProductDesc { get; set; }
}
2、在Models 层文件夹里面,创建商品服务接口IProductService
3、创建服装类ClothingService,继承IProductService
public class ClothingService : IProductService
{
//服装类
public IEnumerable<Product> GetProductList()
{
return new List<Product> {
new Product { ProductID = 1, ProductName = "狼爪双肩背包", ProductPrice = 599, ProductDesc = "无" },
new Product { ProductID = 2, ProductName = "防水男女冲锋衣", ProductPrice = 199, ProductDesc = "无" }
};
}
}
3、创建服装类ClothingService,继承IProductService
//电子产品类
public IEnumerable<Product> GetProductList()
{
return new List<Product> {
new Product { ProductID = 2, ProductName = "华为手机", ProductPrice = 5999, ProductDesc = "无" },
new Product { ProductID = 3, ProductName = "苹果电脑", ProductPrice = 9199, ProductDesc = "无" }
};
}
4、在startup.cs的ConfigureService类中,注册商品服务
public void ConfigureServices(IServiceCollection services)
{
// 注册ProductService
services.AddTransient<Models.IProductService, Models.ClothingService>();
}
5、创建Shop控制器,在构造函数中进行依赖注入
public class ShopController : Controller
{
Models.IProductService _service;
//依赖注入
public ShopController(Models.IProductService service)
{
_service = service;
}
public IActionResult Index()
{
ViewBag.Lists = _service.GetProductList();
return View();
}
}
6、视图显示列表数据
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container" style="margin:30px auto;">
<table class="table table-bordered table-hover">
<tr>
<th>编号</th>
<th>名称</th>
<th>价格</th>
</tr>
@foreach (var item in ViewBag.Lists)
{
<tr>
<td>@item.ProductID</td>
<td>@item.ProductName</td>
<td>@item.ProductPrice.ToString("C2")</td>
</tr>
}
</table>
</div>
</body>
</html>