I am using aspnet 5 and MVC 6.
I have created a view component using the instructions in HERE but when I run my website I get an error
A view component named 'XX' could not be found. AT
@Component.Invoke("XX"))
Here is the structure of my project
namespace Test
{
public class XXViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
return View();
}
}
}
Then in the views folder I have Views/Assets/index.cshtml
<div>
<div class="col-md-4">
@Component.Invoke("XX"))
</div>
</div>
The vc is in Views/Assets/Components/XX/default.cshtml
<div class="col-md-6" id="listOfCustomers">
<table class="table table-condensed">
<span> Test partial View</span>
</table>
</div>
I've had a similar issue. What helped me was the bottom section on the page you used yourself (Avoiding magic strings):
remove 'ViewComponent' suffix from the name of the class (and therefore the constructor) - you would then have:
public class XX : ViewComponent
to use nameof
when invoking the view component:
@Component.Invoke(nameof(XX))
don't forget to use using
of your view component in your main view (Views/Assets/index.cshtml) - in your case @using Test
This might both help you and keep the invoking of your component compile-time saved.
As Joe Audette pointed out, the views might be in an unusual location, but that would result in a different error message.
I came across this question because I had a similar problem but where I want to dynamically load a particular view and needed to ensure that it exists before calling the View() method. This will let you know if the view exists or not. Not fully related with the question though, but hopefully will help people sent by google :)
this.ViewEngine.FindView(this.ViewContext, "test", false).Success
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With