雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

.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天前
赞一波!

文章评论

评论问答