.NET Core 视图组件Component用法
2024-10-14
15
视图组件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>
运行时在以下路径中搜索视图:
/Views/{Controller Name}/Components/{View Component Name}/{View Name}
/Views/Shared/Components/{View Component Name}/{View Name}
/Pages/Shared/Components/{View Component Name}/{View Name}
搜索路径适用于使用控制器 + 视图和 Pages Razor 的项目。
调用Component
@await Component.InvokeAsync("Content")
//带参数调用
@await Component.InvokeAsync("Content", new { name="content" })
更新于:4天前赞一波!
相关文章
- ASP.NET Core 2.1中的ActionResult<T>
- .NET Core 3.0创建一个单独的可执行文件
- 在ASP.NET Core 2.1中使用HttpClientFactory的3种方法
- .NET Core MVC应用程序创建教程
- .NET Core中的File和PhysicalFile
- .NET Core 读取配置文件方法
- .NET Core 管道模型中间件及管道模拟实现
- ASP.NET Core多环境配置
- .NET Core 日志配置,NLog配置示例
- ASP.NET Core主机和应用启动流程
- .NET Core SkiaSharp替代System.Drawing的用法
- .NET Core 3.X路由中间件和终结点中间件
- .Net报错Could not find a part of the path bin\roslyn\csc.exe
- IIS中.NET Core报错HTTP Error 500.31 - ANCM Failed to Find Native Dependencies
- .NET Core分部视图PartialView用法
- ASP.NET Core的三种部署方式
- .NET Core中使用System.Drawing处理图像
- .NET Core Razor Page ajax请求返回400 Bad request
- .NET Core上传文件报Access xxx.tmp is denied错误
- ASP.NET Core 使用Razor code blocks替代@helper
文章评论
评论问答