ViewComponents in Areas

I may be wrong (I can't find any documentation on how to do this any other way). When you create the ViewComponent in scope, the search paths are wrong:

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

      

The /Areas/Test/Views/Components/Hello/Default.cshtml

following exception was thrown instead of searching the view :

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.

      

I am invoking the view by doing the following: (c /Views/Home/Index.cshtml

)

@Component.Invoke("Hello")

      

There seems to be no way to include an area to call the view.

Any ideas as to the correct way to call the ViewComponent from within the District or if this is not correct and I am making a mistake.

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

+3


source to share


3 answers


The attribute Area

can only be used with controllers. When you make a request for a view within a scope, and if that view has any view components that they reference, then MVC looks for view views in a specific order.
Below is the difference in how the view component of the view looks when the request matches a scoped controller rather than a non scoped controller.

Example:



  • Browse the component view search path for the type query /Admin/Home/Index

    , where Admin

    is the scope.

    • /Areas/Admin/Views/Home/Components/Products/Default.cshtml
    • /Areas/Admin/Views/Shared/Components/Products/Default.cshtml
    • /Views/Shared/Components/Products/Default.cshtml.
  • Browse Component View Search Path for Type Query /Home/Index

    (Query Without Scope)

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


source


When using your component, you should be able to use the absolute path to your view, for example this view ("~ / Areas / Test / Views / Components / Hello / Default.cshtml") to fix your problem.



+1


source


ViewComponents files should be placed like this:

ViewComponent in MVC scope

Then call from the view:

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

      

This is a job for me. Hope this helps!

+1


source







All Articles