I have come across what appears to be a limitation with using ViewComponent's in ASP.NET Core 2.0.
We have a ViewComponent that works absolutely perfectly when invoked from a layout page. When we invoke the same ViewComponent from a Razor page we get the following error.
The model item passed into the ViewDataDictionary is of type <viewcomponenttype> but this ViewDataDictionary instance requires a model item of type <parentpagetype>
The ViewComponent seems to expect the model type of the parent Razor page to be passed, rather than the model type defined for the ViewComponent.
I haven't come across any examples of a ViewComponent being used from a Razor page, they only seem to be used from layout pages (which don't have models).
Can someone give me a definitive yes or no to the question: can you use ViewComponent's within a Razor page, and if so, how?
Additionally on the answer by Iztoksson, if you are well versed in using tag helpers, you may use it in invoking the ViewComponent
<div>
<vc:SampleView testVm = "new { testVm = new Models.TestVm() }"></vc:SampleView>
</div>
although you have to register the viewcomponents tag in the
ViewImports.cshtml
file and add the following line to the existing code:
@addTagHelper *, RazorPages
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