视图组件用于封装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 片段,适合用在布局页、侧边栏、导航菜单等需要复用的地方。
视图组件类通常继承自 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));
}
}
}
视图组件的视图文件应放在 Views/Shared/Components/{ViewComponentName}/Default.cshtml 或 Views/{Controller}/Components/{ViewComponentName}/Default.cshtml。
其中 {ViewComponentName} 是去掉 "ViewComponent" 后缀后的类名(如 Notification)。
// 示例:Notification 视图文件路径Views/Shared/Components/Notification/Default.cshtml
@model IEnumerable<dynamic>
<div class="notification-panel">
<h4>通知 <span class="badge">@Model.Count()</span></h4>
<ul>
@foreach (var item in Model)
{
<li>@item.Message (@item.Time.ToString("HH:mm"))</li>
}
</ul>
</div>
使用 Component.InvokeAsync 方法在 Razor 视图中异步调用视图组件。
@await Component.InvokeAsync("Notification", new { maxNotifications = 3 })
也可以使用同步方式(不推荐在生产环境使用):
@{ Component.Invoke("Notification", 3); }
如果需要执行异步操作(如数据库查询),可以使用 InvokeAsync 方法:
public async Task<IViewComponentResult> InvokeAsync(int maxNotifications)
{
var notifications = await _notificationService.GetRecentAsync(maxNotifications);
return View(notifications);
}
基本上就这些。创建视图组件就是写一个类、配一个视图、然后在页面上调用。结构清晰,复用方便,适合处理局部动态内容。
以上就是ASP.NET Core 中的视图组件如何创建?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号