Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use ViewComponents with Razor pages?

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?

like image 307
DomBurf Avatar asked Mar 06 '23 09:03

DomBurf


1 Answers

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
like image 145
Albert Laure Avatar answered Mar 21 '23 07:03

Albert Laure