Search code examples
c#.net-corerazor

How to return a correct layout partial view with Class/IViewComponentResult and not get the route with Class/Method/~/view/shared/_pg.cshtml .Net Core


in my _pageLayout , I try to do partial view like this

@{Layout = "~/Views/Shared/_Layout.cshtml";} 
<div> @await Component.InvokeAsync("_PageMenu") </div>

and I Create a Folder called Component and a Class called _PageMenuViewComponent

public class _PageMenuViewComponent:ViewComponent
{
    private readonly SYS_menu_mstr_Repo _sys_menu_mstr_repo;
    public _PageMenuViewComponent(SYS_menu_mstr_Repo sys_menu_mstr_repo)
    {
        _sys_menu_mstr_repo = sys_menu_mstr_repo;
    }
    public IViewComponentResult Invoke()
    {
        var menuList = _sys_menu_mstr_repo.Get_ALL_Menu_Mstr();
        return View("~/View/Shared/_PageMenu.cshtml", menuList);
    }
}

and always get route like this:

InvalidOperationException: The view 'Components/_PageMenu/~View/Shared/_PageMenu.cshtml' was not found. The following locations were searched:
~View/Shared/_PageMenu.cshtml

AspNetCore.Views_Shared__PageLayout.ExecuteAsync() in _PageLayout.cshtml
+
        @await Component.InvokeAsync("_PageMenu")

I don't want to change MapControllerRoute in startup.cs Because it is just a partialview for layout.

It will be needed when I write something in Controller after.

How could I return the exact view with model in my class/method ?


Solution

    1. Inside of Shared folder you have to crate a Components folder and then _PageMenu folder. Put the partial view there.

    2. Create class in Controllers folder

    [ViewComponent(Name = "_PageMenu")]
    public _PageMenuViewComponent(SYS_menu_mstr_Repo sys_menu_mstr_repo)
    {
    .....
    return View("_PageMenu", menuList);
    
    }