ASP.NET Core 中的视图组件如何创建?

来源:这里教程网 时间:2026-02-21 17:28:37 作者:

在 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.cshtmlViews/{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>

3. 在视图中调用视图组件

使用 Component.InvokeAsync 方法在 Razor 视图中异步调用视图组件。

@await Component.InvokeAsync("Notification", new { maxNotifications = 3 })

也可以使用同步方式(不推荐在生产环境使用):

@{ Component.Invoke("Notification", 3); }

4. 异步支持(可选)

如果需要执行异步操作(如数据库查询),可以使用 InvokeAsync 方法:

public async Task<IViewComponentResult> InvokeAsync(int maxNotifications)
{
    var notifications = await _notificationService.GetRecentAsync(maxNotifications);
    return View(notifications);
}

基本上就这些。创建视图组件就是写一个类、配一个视图、然后在页面上调用。结构清晰,复用方便,适合处理局部动态内容。

相关推荐