使用 Razor Pages 在 Asp.NET Core 2.2 中找不到 ViewComponent
ViewComponent not found in Asp.NET Core 2.2 using Razor Pages
我创建了一个非常简单的视图组件(/ViewComponents/MenuViewComponent.cs
):
namespace MySite.ViewComponents
{
public class MenuViewComponent : ViewComponent
{
public Task<IViewComponentResult> InvokeAsync()
{
return Task.FromResult((IViewComponentResult)View("Default"));
}
}
}
查看部分在这里(/Pages/Components/Menu/Default.cshtml
):
<div>Menu</div>
我正在从 _Layout.cshtml
文件中调用 菜单 ,如下所示:
@await Component.InvokeAsync("MenuViewComponent");
查看页面时出现以下错误消息:
InvalidOperationException: A view component named 'MenuViewComponent' could not be found.
A view component must be a public non-abstract class, not contain any generic parameters,
and either be decorated with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix.
A view component must not be decorated with 'NonViewComponentAttribute'.
问题:
我缺少什么才能使它正常工作?
确保组件视图位于如下所述的搜索路径中
引用View components in ASP.NET Core
并且在调用组件时只需使用不带后缀的名称
@await Component.InvokeAsync("Menu")
我创建了一个非常简单的视图组件(/ViewComponents/MenuViewComponent.cs
):
namespace MySite.ViewComponents
{
public class MenuViewComponent : ViewComponent
{
public Task<IViewComponentResult> InvokeAsync()
{
return Task.FromResult((IViewComponentResult)View("Default"));
}
}
}
查看部分在这里(/Pages/Components/Menu/Default.cshtml
):
<div>Menu</div>
我正在从 _Layout.cshtml
文件中调用 菜单 ,如下所示:
@await Component.InvokeAsync("MenuViewComponent");
查看页面时出现以下错误消息:
InvalidOperationException: A view component named 'MenuViewComponent' could not be found.
A view component must be a public non-abstract class, not contain any generic parameters,
and either be decorated with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix.
A view component must not be decorated with 'NonViewComponentAttribute'.
问题:
我缺少什么才能使它正常工作?
确保组件视图位于如下所述的搜索路径中
引用View components in ASP.NET Core
并且在调用组件时只需使用不带后缀的名称
@await Component.InvokeAsync("Menu")