【问题标题】:Error in asp .NET core: Partial component doesn't workasp .NET core 中的错误:部分组件不起作用
【发布时间】:2020-12-30 05:59:46
【问题描述】:

InvalidOperationException:找不到名为“../../Shared/Component”的视图组件。视图组件必须是公共的非抽象类,不包含任何通用参数,并且要么用“ViewComponentAttribute”装饰,要么具有以“ViewComponent”后缀结尾的类名。视图组件不能用“NonViewComponentAttribute”修饰。

Screenshot

@model ShopApp.WEBUI.ViewModels.ProductViewModel

@{
    var popularClass = Model.Products.Count > 2 ? "popular" : "";
    var products = Model.Products;
    var categories = Model.Categories;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        main {
            display: inline;
        }

        .popular {
            color: orangered;
        }
    </style>
</head>
<body>
    @await Html.PartialAsync(@"../../shared/_navbar")
    @await Html.PartialAsync(@"../../shared/_header");

    <main>
        <div class="container">
            <div class="row">
                <div class="col-md-4">
                    @await Component.InvokeAsync(@"../../Shared/Component",categories)
                </div>
                <div class="col-md-8">
                    @if (products.Count == 0)
                    {
                        @await Html.PartialAsync(@"../../shared/_NoProduc");
                    }
                    else
                    {
                        <div class="row">
                            @foreach (var product in products)
                            {
                                <div class="col-md-2">
                                    @await Html.PartialAsync(@"../../shared/_product", product)
                                </div>
                            }
                        </div>
                    }
                </div>
            </div>
        </div>
    </main>
</body>
</html>

【问题讨论】:

  • Component.InvokeAsync 正在寻找您的视图组件名称,而不是路径

标签: c# asp.net-core asp.net-core-mvc asp.net-core-viewcomponent


【解决方案1】:

Change name of component folder to Components 然后在其中创建具有 Categories 名称的文件夹,然后将 Default.cshtml 放入其中。

这样打电话

@await Component.InvokeAsync("Categories", new { place your parameters here })

CategoriesViewComponent 必须继承自 ViewComponent

您的参数必须在 CategoriesViewComponent 类的 InvokeAsynk 方法中声明,并在您要调用此组件的地方使用它的名称:new { parameter1 = "value" }

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 1970-01-01
    • 2020-07-25
    • 2018-12-20
    • 1970-01-01
    • 2020-04-03
    • 2016-12-14
    • 2020-07-12
    • 2017-11-12
    相关资源
    最近更新 更多