本系列学习笔记均来源于B站UP主”软件工艺师“的学习视频,学习连接如下:
https://www.bilibili.com/video/BV1c441167KQ
ASP.NET Core 3.x 学习笔记(4)——View Component
紧接前面文章的内容,建立一个复用的控件,在项目的每个页面都显示公司的总人数和部门的平均人数。这时候就需要使用到 View Component。
View Component
为什么使用其它方式不可行?
- 为什么 Partial View 不行?因为没法添加业务逻辑;
- 如果在 Controller 里面写(业务逻辑)呢?那就无法实现任意复用;
- Child Action 呢?开销太大。它需要走完整个 Controller 的生命周期。
View Component 的优势
- View Component 类似 Partial View,但是还带有一个迷你的 Controller,可以在这里写业务逻辑,并将业务逻辑处理结果传给 Model 属性,然后带给 View。(强大且轻量)
- 可以使用 Razor 语法来渲染 View Component
具体实现
-
CompanySummary 的 Model 在前文中已经建立,并在 DepartmentService 中建立返回 CompanySummary 信息的方法。如下:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ASPNETCore_Learning_Three.Models { public class CompanySummary { public int EmployeeCount { get; set; } public int AverageDepartmentEmployeeCount { get; set; } } }
public Task<CompanySummary> GetCompanySummary() { return Task.Run(() => { return new CompanySummary { EmployeeCount = _departments.Sum(x => x.EmployeeCount), AverageDepartmentEmployeeCount = (int)_departments.Average(x => x.EmployeeCount) }; }); }
-
首先,建立 ViewComponents/CompanySummaryViewComponent.cs 类,代码如下:
using ASPNETCore_Learning_Three.Services; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ASPNETCore_Learning_Three.ViewComponents { public class CompanySummaryViewComponent: ViewComponent { private readonly IDepartmentService _departmentService; public CompanySummaryViewComponent(IDepartmentService departmentService) { this._departmentService = departmentService; } public async Task<IViewComponentResult> InvokeAsync(string title) { ViewBag.Title = title; var summary = await _departmentService.GetCompanySummary(); return View(summary); } } }
- CompanySummary 信息通过 DepartmentService 获取,故构造函数中注入 DepartmentService;
- InvokeAsync 异步返回结果到页面;
- InvokeAsync 通过 ViewBag 传递参数到页面
-
建立显示 CompanySummary 信息的视图:Shared/Components/CompanySummary/Default.cshtml。视图路径中 Shared/Components 为固定约定。代码如下:
@model ASPNETCore_Learning_Three.Models.CompanySummary <div class="small"> <div class="row h3">@ViewBag.Title</div> <div class="row"> <div class="col-md-8">员工总数:</div> <div class="col-md-4">@Model.EmployeeCount</div> </div> <div class="row"> <div class="col-md-8">部门平均人数:</div> <div class="col-md-4">@Model.AverageDepartmentEmployeeCount</div> </div> </div>
-
在需要使用到 CompanySummary 信息的视图中添加。代码如下:
@using ASPNETCore_Learning_Three.Models @model IEnumerable<Department> <div class="row"> <div class="col-md-10 offset-md-2"> <table class="table"> <tr> <th>Name</th> <th>Location</th> <th>Employee</th> <th>操作</th> </tr> @Html.DisplayForModel() </table> </div> </div> <div class="row"> <div class="col-md-2"> @await Component.InvokeAsync("CompanySummary", new { title = "部门列表汇总" }); <vc:company-summary title="部门列表汇总2"></vc:company-summary> </div> <div class="col-md-4 offset-md-2"> <a asp-action="Add">Add</a> </div> </div>