• 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>
    
  • 相关阅读:
    Django RequestContext用法
    【Django】Django命令(Manager.py)
    Django:快速搭建简单的Blog
    win7下安装Ubuntukylin-14.04双系统
    activity生命周期
    Activity(三)
    BZOJ 3944 Sum 解题报告
    BZOJ 3901 棋盘游戏 解题报告
    web框架之socket
    新式类__new__()方法
  • 原文地址:https://www.cnblogs.com/easy5weikai/p/13030579.html
Copyright © 2020-2023  润新知