ViewComponentAttribute' 或具有以 'ViewComponent' 后缀结尾的 class 名称

ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix

数据控制器

   public class FilterlistViewComponent : ViewComponent
    {
        
        public async Task<IViewComponentResult> InvokeAsync(string text)
        {
            var result = text;
            return View(result);
        }

    }

Filter.cshtml

<div> 
@await Component.InvokeAsync("Filterlist", new { text = "test" })
</div>

file structure

我完全应用了以下解决方案,但出现以下错误。

screenshot of the error

System.InvalidOperationException: A view component named 'Filterlist' 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'.

确保不要放置 ViewComponent class,如下所示,它位于内部DataController:

public class DataController : Controller
{
    public IActionResult Filter()
    {
        return View();
    }
    public class FilterlistViewComponent : ViewComponent
    {

        public async Task<IViewComponentResult> InvokeAsync(string text)
        {
            var result = text;
            return View(result);
        }

    }
}

您需要将它放在控制器之外class,它可以位于任何其他文件夹中。

例如:

此外,在 InvokeAsync 方法中,您 return 使用 result 查看并且 result 不匹配 视图名称 视图模型数据。所以当你传new{ text = "test" }给ViewComponent时,你会return测试视图,也就是说你需要把Default.cshtml改成test.cshtml或者只添加一个新的视图[=16] =] 在你的 Data/Components/Filterlist.