区域中的 ViewComponents

ViewComponents in Areas

我可能做错了(我找不到任何关于如何以其他方式做的文档)。 在 Area 中创建 ViewComponent 时,搜索路径不正确:

namespace HelloWorld
{
    [Area("Test")]
    public class HelloViewComponent : ViewComponent
    {
        public IViewComponentResult Invoke()
        {
            return View();
        }
    }
}

不是在 /Areas/Test/Views/Components/Hello/Default.cshtml 处搜索视图,而是抛出以下异常:

InvalidOperationException: The view 'Components/Hello/Default' was not found. The following locations were searched:
/Views/Home/Components/Hello/Default.cshtml
/Views/Shared/Components/Hello/Default.cshtml.

我通过执行以下操作调用视图:(在 /Views/Home/Index.cshtml

@Component.Invoke("Hello")

似乎没有办法包含调用视图的区域。

关于从区域内调用 ViewComponent 的正确方法的任何想法,或者如果以上不正确并且我犯了错误。

https://github.com/aspnet/Mvc/issues/2640

Area 属性只能与控制器一起使用。当您向某个区域内的视图发出请求时,如果该视图中引用了任何视图组件,则 MVC 会按特定顺序查找视图组件的视图。
以下是当请求匹配基于区域的控制器与非区域控制器时,如何搜索视图组件视图的差异。

示例:

  1. View Component 的视图搜索路径,如 /Admin/Home/Index 的请求,其中 Admin 是一个区域。

    • /Areas/Admin/Views/Home/Components/Products/Default.cshtml
    • /Areas/Admin/Views/Shared/Components/Products/Default.cshtml
    • /Views/Shared/Components/Products/Default.cshtml.
  2. View Component 的view搜索路径为类似/Home/Index的请求(非区域请求)

    • /Views/Home/Components/Products/Default.cshtml
    • /Views/Shared/Components/Products/Default.cshtml.

使用您的组件时,您应该能够像这样使用视图的绝对路径 View("~/Areas/Test/Views/Components/Hello/Default.cshtml") 来解决您的问题。

ViewComponents 文件应放置如下:

然后从视图调用:

@await Component.InvokeAsync(typeof(Swastika.Web.Start.Areas.Portal.ViewComponents.MainSidebar));

这对我有用。希望对您有所帮助!