视图组件Component
视图组件与分部视图类似,但它们的功能更加强大。 视图组件不使用模型绑定,并且仅依赖调用时提供的数据。 本文是使用控制器和视图编写的,但视图组件也与 Razor Pages 一起编写。
什么是视图组件?
什么时候用视图组件?
视图组件可用于具有可重用呈现逻辑(对分部视图来说过于复杂)的任何位置,例如:
使用Component示例:
在Pages/Components目录下添加视图组件类
ContentViewComponent.cs
- namespace MyMvc.Pages.Components
- {
- public class ContentViewComponent : ViewComponent
- {
- private Database database;
- public ContentViewComponent(Database database) {
- this.database = database;
- }
- public async Task<IViewComponentResult> InvokeAsync()
- {
- var list = await database.GetListAsync();
- return View(string.Empty, string.Join(",", list));
- }
- }
- }
在Pages/Shared/Components/Content目录下添加视图文件
Default.cshtml
- @model string
- @{
- }
- <h2>
- Content component.
- </h2>
- <h3>
- @Model
- </h3>
运行时在以下路径中搜索视图:
搜索路径适用于使用控制器 + 视图和 Pages Razor 的项目。
调用Component
- @await Component.InvokeAsync("Content")
- //带参数调用
- @await Component.InvokeAsync("Content", new { name="content" })