05. Asp.Net Core 3.x 笔记 ViewComponet
为什么使用ViewComponet
- PartView 不能实现业务逻辑
- ChildAction 要使用Controller的整个生命周期,开销大
如何使用
- 新建
ViewComponent
类:
新建文件ViewComponents
,在其里面新建类CompanySummaryViewComponent
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);
}
}
- 新建ViewComponent视图
在View/Shard
文件夹下新建Components/CompanySummary
文件夹,在里面新建Default.cshtml
@model Three.Models.CompanySummary
<div class="small">
<div class="row h3">
Company Summary
</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.AvgDepartmentEmployeeCount
</div>
</div>
- 使用ViewComponent
1.方式(一)
<div class="row">
<div class="col-md-4">
@await Component.InvokeAsync("CompanySummary", new { title ="汇总"})
</div>
</div>
2.方式(二)
在_ViewImports.cshtml
中导入本项目的TagHelper
@addTagHelper "*, Three"
CompanySummaryViewComponent
对用的TagHelper是 <vc:company-summary>
<div class="row">
<div class="col-md-4">
<vc:company-summary title="汇总2"></vc:company-summary>
</div>
</div>