Steve
Steve

Reputation: 1316

ASP.NET Core - Razor not checking for view embeded in assembly

I am trying to set up a pair of .NET Core project where one is a class library including a ViewComponent and the other is an ASP.NET Core MVC application which makes use of that component.

I followed the guide here: http://www.strathweb.com/2016/01/re-using-external-view-components-in-asp-net-5-asp-net-mvc-6/

However, I can't seem to get this working. I keep getting:

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

The component itself:

public class TestViewComponent : ViewComponent
{
    public TestViewComponent()
    {
    }

    public IViewComponentResult Invoke()
    {
        return View();
    }
}

The corresponding view (file path is Views/Shared/Components/Test/Default.cshtml):

<p>Hello from test component</p>

Relevant bit from ConfigureServices to tell Razor to look for views in the assembly:

services.Configure<RazorViewEngineOptions>(o =>
{
    o.FileProviders.Add(new EmbeddedFileProvider(
        typeof(TestViewComponent).GetTypeInfo().Assembly, "Test.Components"));
});

project.json from the class library project:

"buildOptions": {
  "embed": {
    "include": [ "Views" ]
  } 
},

and finally, at the bottom of _Layout.cshtml in the MVC project:

    @await Component.InvokeAsync("Test")
</body>
</html>

Things I've tried:

Upvotes: 1

Views: 1793

Answers (2)

jag
jag

Reputation: 536

I had this problem and it was resolved by changing Build Action property on the View from None to Embedded Resource.

  1. Right click view in Solution Explorer.
  2. Select Properties.
  3. Change Build Action to Embedded Resource.

Alternatively, if you want to automatically add all Views as Embedded Resources, you can add this ItemGroup to your .csproj file:

<ItemGroup> <EmbeddedResource Include="Views\**\*.cshtml" /> </ItemGroup>

Upvotes: 0

korn3l
korn3l

Reputation: 143

I managed to get it working by removing the base namespace.

o.FileProviders.Add(new EmbeddedFileProvider(typeof(TestViewComponent) .GetTypeInfo().Assembly));

It seems that adding the base namespace doesn't work as expected. Don't really know why

Upvotes: 4

Related Questions