Search code examples
c#asp.netasp.net-coreclass-library

InvalidOperationException: The view was not found


I have an ASP.Net project and I want to use a class library project for creating reusable Razor view components. I added AspNetCore.Mvc and AspNetCore.Razor.Tools references to my class library project.

I create the ViewComponent class inside Components/DataTableComponent.cs file:

namespace Rasha.Utility.Components
{
    public class DataTableComponent:ViewComponent
    {
        public async Task<IViewComponentResult> InvokeAsync()
        {
            var model = new DataTableModel()
            {
                Name = "Alliiiiiiiiiiiiiiiii"
            };
            return View("Default.cshtml", model);
        }
    }
}

And view inside Views/Shared/Components/DataTableComponent/Default.cshtml file.

This is my class library .csproj file:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Tools" Version="1.1.0-preview4-final" />
  </ItemGroup>

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

Why I getting this error:

InvalidOperationException: The view 'Components/DataTableComponent/Default.cshtml' was not found. The following locations were searched: /Areas/Administration/Views/Customer/Default.cshtml

It seems the compiler looking for view in my MVC project instead of the class library project.

Thanks.


Solution

  • My dream came true:

    Creating a Razor Class Library project in ASP.NET Core is available now.