I created an ASP.NET Core MVC (.net core 8) project. I added a dummy ViewComponent and each time I run the application, I get the following error:
An unhandled exception occurred while processing the request.
InvalidOperationException: The view 'Components/Dummy/Default' was not found. The following locations were searched:
/Views/Home/Components/Dummy/Default.cshtml
/Views/Shared/Components/Dummy/Default.cshtml
I've checked MicroSoft documentation and I've checked on forums like StackOverflow but nothing is working.
Any help would be very much appreciated.
Here is the solution explorer view:
Here is the ViewComponent class:
public class DummyViewComponent : ViewComponent
{
public DummyViewComponent()
{
}
public async Task<IViewComponentResult> InvokeAsync()
{
await Task.Delay(TimeSpan.FromMilliseconds(1));
return View();
}
}
Here is the CSHTML:
<div>
Dummy view component!
</div>
And here is where it is being invoked in the home (index) page:
@{
ViewData["Title"] = "Overview";
}
@section Styles {
}
@await Component.InvokeAsync("Dummy")
@section Scripts {
}
As you can see, this is quite straight forward - I really cannot see where the issue is.
Many thanks in advance.
What you have done seems no mistake. Here are some potential causes and solutions you could try:
Runtime compilation is not enabled by default, install the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
package and modify the Program.cs:
builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
Try to specify the view path:
public async Task<IViewComponentResult> InvokeAsync()
{
await Task.Delay(TimeSpan.FromMilliseconds(1));
return View("~/Views/Shared/Components/Dummy/Default.cshtml");
}
Check if there are any issues with the compilation of your views. If you cannot troubleshooting for this, you can remove all of the other html codes except the view components and then check if it works or not.
Right-click the file(Views/Shared/Components/Dummy/Default.cshtml
) in Visual Studio, select Properties
, and verify the Build Action
is set to Content.
Try to right-click the project, choose Clean
and then choose Rebuild
. After doing the two approaches, run the application again.
Check if you write any customized middlewares or filters which may influence the view components.