视图组件用于封装UI逻辑并生成局部视图,适合复用场景。1. 创建继承ViewComponent的类,命名以ViewComponent结尾或加[ViewComponent]特性;2. 在Views/Shared/Components/{Name}/Default.cshtml创建对应视图;3. 在Razor视图中用@await Component.InvokeAsync("Name", args)调用;4. 支持异步方法InvokeAsync处理耗时操作。结构清晰,便于维护。

在 ASP.NET Core 中,视图组件(View Component)是一种可重用的组件,用于封装页面逻辑并生成部分视图内容。它类似于控制器,但更专注于 UI 片段,适合用在布局页、侧边栏、导航菜单等需要复用的地方。
1. 创建视图组件类
视图组件类通常继承自 ViewComponent,可以放在项目中的任意位置,但推荐放在 ViewComponents 文件夹中。
命名要求:类名以 "ViewComponent" 结尾,或使用 [ViewComponent] 特性标记。
// 示例:创建一个显示用户通知的视图组件
using Microsoft.AspNetCore.Mvc;
namespace MyWebApp.ViewComponents
{
public class NotificationViewComponent : ViewComponent
{
public IViewComponentResult Invoke(int maxNotifications = 5)
{
// 模拟数据
var notifications = new[]
{
new { Message = "你有一条新消息", Time = DateTime.Now.AddMinutes(-10) },
new { Message = "系统更新提醒", Time = DateTime.Now.AddMinutes(-30) }
};
return View(notifications.Take(maxNotifications));
}
}
}
2. 创建视图组件对应的视图文件
视图组件的视图文件应放在 Views/Shared/Components/{ViewComponentName}/Default.cshtml 或 Views/{Controller}/Components/{ViewComponentName}/Default.cshtml。
其中 {ViewComponentName} 是去掉 "ViewComponent" 后缀后的类名(如 Notification)。
// 示例:Notification 视图文件路径Views/Shared/Components/Notification/Default.cshtml
云模块_YunMOK网站管理系统采用PHP+MYSQL为编程语言,搭载自主研发的模块化引擎驱动技术,实现可视化拖拽无技术创建并管理网站!如你所想,无限可能,支持创建任何网站:企业、商城、O2O、门户、论坛、人才等一块儿搞定!永久免费授权,包括商业用途; 默认内置三套免费模板。PC网站+手机网站+适配微信+文章管理+产品管理+SEO优化+组件扩展+NEW Login界面.....目测已经遥遥领先..
@model IEnumerable通知 @Model.Count()
@foreach (var item in Model) {
- @item.Message (@item.Time.ToString("HH:mm"))
}
3. 在视图中调用视图组件
使用 Component.InvokeAsync 方法在 Razor 视图中异步调用视图组件。
@await Component.InvokeAsync("Notification", new { maxNotifications = 3 })
也可以使用同步方式(不推荐在生产环境使用):
@{ Component.Invoke("Notification", 3); }
4. 异步支持(可选)
如果需要执行异步操作(如数据库查询),可以使用 InvokeAsync 方法:
public async TaskInvokeAsync(int maxNotifications) { var notifications = await _notificationService.GetRecentAsync(maxNotifications); return View(notifications); }
基本上就这些。创建视图组件就是写一个类、配一个视图、然后在页面上调用。结构清晰,复用方便,适合处理局部动态内容。









