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>
posted @ 2020-06-02 12:57  easy5  阅读(139)  评论(0编辑  收藏  举报