Error in asp .NET core: Partial component doesn't work

669 Views Asked by At

InvalidOperationException: A view component named '../../Shared/Component' 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'.

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>
1

There are 1 best solutions below

0
On

Change name of component folder to Components and then create folder in that with Categories name and then put Default.cshtml in it.

call like this

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

CategoriesViewComponent must inheited from ViewComponent

your parameters must be declared in the InvokeAsynk method of CategoriesViewComponent class and use it with its name where you want to Invoke this component: new { parameter1 = "value" }