Home > front end >  How to specify a view component under a sub folder within shared/components
How to specify a view component under a sub folder within shared/components

Time:11-06

I get an error anytime I try to specify a view component from a razor page which lies anywhere but directly under the folder structure of shared/components. For example, shared/components/UserCRUD/{mycomponent} will not work. See the pictures below:

where I include the view component. Note that I have also tried this with typeof() and nameof(), to which the intellisense correctly identifies the correct location under the sub folder.

enter image description here

My relevant folder structure:

enter image description here

The namespace I am using. Note that I have also tried naming this with the "ViewComponent" suffix to no end.

enter image description here

And finally the exception. The most strange thing is that the exception isn't looking at the path I handed it. It's completely omitting UserCRUD.

enter image description here

CodePudding user response:

The folder setup you have doesn't match with the default view location formats.
Even adjusting those doesn't seem to work - or at least I don't succeed in it.

No combination of fixed values and predefined placeholders ({0} view name, {1} page name) seem to give the expected result; there's something with that Components segment that always get added automatically.


Below does work.

In AdminDashboard/Index.cshtml include that UserTable component as below.
You can also keep your current call since that one seems to work.

@await Component.InvokeAsync("UserTable")

Adjust your UserTable component in UserTable.cs by returning the full path to the corresponding view, being /Areas/Identity/Pages/Shared/Components/UserCRUD/UserTable/UserTable.cshtml.

public class UserTable : ViewComponent
{
    public IViewComponentResult Invoke(string module)
        => View("/Areas/Identity/Pages/Shared/Components/UserCRUD/UserTable/UserTable.cshtml");
}

You'll have to do similarly for the other views in that UserCRUD folder.

  • Related