【问题标题】:ViewComponent not found in Asp.NET Core 2.2 using Razor Pages在使用 Razor 页面的 Asp.NET Core 2.2 中找不到 ViewComponent
【发布时间】:2019-12-27 19:23:17
【问题描述】:

我创建了一个非常简单的视图组件(/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 文件中调用 Menu,如下所示:

@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'.

问题
让这个工作我缺少什么?

【问题讨论】:

  • 确保组件视图在搜索路径中,并且在调用时只使用不带后缀的名称@await Component.InvokeAsync("Menu")
  • @Nkosi 我尝试移动文件以匹配您链接中的建议,但没有任何效果。但是您建议仅使用“菜单”调用是我的解决方案。谢谢!

标签: c# razor asp.net-core-2.2 asp.net-core-viewcomponent


【解决方案1】:

确保组件视图位于搜索路径中,如下所述

参考View components in ASP.NET Core

并且在调用组件时只需使用不带后缀的名称

@await Component.InvokeAsync("Menu") 

【讨论】:

    猜你喜欢
    • 2019-11-12
    • 1970-01-01
    • 2020-05-06
    • 2020-02-09
    • 2019-09-17
    • 2020-08-14
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    相关资源
    最近更新 更多