区域中的ViewComponent

log*_*kal 6 asp.net-core-mvc

我可能做错了此事(我无法找到任何其他方式进行操作的文档)。在区域中创建ViewComponent时,搜索路径不正确:

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

而不是在/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.
Run Code Online (Sandbox Code Playgroud)

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

@Component.Invoke("Hello")
Run Code Online (Sandbox Code Playgroud)

似乎没有办法包括从中调用视图的区域。

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

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

Kir*_*lla 6

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. 查看组件的视图搜索路径,例如/Home/Index(非区域请求)的请求

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


Wan*_*ton 5

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


小智 5

ViewComponents 文件应放置如下:

MVC 区域中的 ViewComponent

然后从视图调用:

@await Component.InvokeAsync(typeof(Swastika.Web.Start.Areas.Portal.ViewComponents.MainSidebar));
Run Code Online (Sandbox Code Playgroud)

这对我有用。我希望它有帮助!