.net core 3.x 中的ViewComponent使用方式 电脑版发表于:2020/4/16 15:17 ># ViewComponent 基础 [TOC] <br/> ###### 创建一个.NetCore 3.x的MVC项目 。。。 ###### 实验目的 ------------ ```mermaid graph TD A[用户网页请求] -.->|IIS| B(HomeController) B --> C{*.cshtml中是否有ViewComponent} C -->|有| D[进入ViewComponent迷你控制器中] C -->E[不做任何处理] D -->|有| X[返回对应的处理页面] X -->O[结束] E -->O[结束] style A fill:#3498db,stroke:#2980b9,stroke-width:4px,fill-opacity:0.5 style B fill:#ccf,stroke:#9980FA,stroke-width:4px,stroke-dasharray: 10,5 style C fill:#7bed9f,stroke:#2ed573,stroke-width:4px,stroke-dasharray: 10,5 style D fill:#ccf,stroke:#9980FA,stroke-width:4px,stroke-dasharray: 10,5 style X fill:#ED4C67,color:#fff,stroke:#B53471,stroke-width:4px,stroke-dasharray: 10,5 style E fill:#000,color:#fff style O fill:#000,color:#fff ``` ###### 开始实验 ------------ >创建 <font style="color:#FFC312">**ViewComponents**</font> 创建 <font style="color:#2ed573">**CounterViewComponent.cs**</font> <br/>  <br/> ><font style="color:#2ed573;">**CounterViewComponent.cs**</font>内容如下 <br/> ```csharp public class CounterViewComponent:ViewComponent { public static int i = 0; private readonly ILogger<HomeController> _logger; public CounterViewComponent(ILogger<HomeController> logger) { _logger = logger; } public async Task<IViewComponentResult> InvokeAsync() { var controller = RouteData.Values["controller"].ToString(); var action = RouteData.Values["action"].ToString(); if (!string.IsNullOrWhiteSpace(controller) && !string.IsNullOrWhiteSpace(action)) { var pageId = $"{controller}-{action}"; i = i++; return View("Default", pageId +": "+ i); } throw new Exception("Cannot get pageId"); } } ``` <br/> >在 <font style="color:#FFC312">**Views**</font>文件夹创建下列对应文档与路径 <br/>  <br/> >在**HomeController**中的**Index**视图上添加如下代码 在这之前我把layer给去掉了 <br/> ```html <h1>@await Component.InvokeAsync("Counter")</h1> ``` ###### 实验结果 ------------ 