vassilag
vassilag

Reputation: 470

Nested ViewComponent, is it possible?

Trying to implement the layout of the picture below, I would like to ask about best practices regarding the architecture of the page layout. Is it better to have independent ViewComponents in every section of the page or partial views? Is it possible to have nested ViewComponents?

The idea is to reuse the sections in other positions in different pages. The concept is very similar to Web parts we used to have but now I try to implement something like this with Asp. Net Core.

Basic layout

Upvotes: 6

Views: 5314

Answers (1)

Dmitry Pavlov
Dmitry Pavlov

Reputation: 28290

Yes, it is possible to have nested View Components.

What is important to keep in mind:

  • You should keep your views structure under Components folder plain
  • You should keep your ViewComponent classes under ViewComponent folder plain
  • You should control infinite loops yourself when you nest component1 into component2 and at the same time component2 into component1

NOTE: most likely you will need your components to include edit/save/update functionalities. As far as I understand, View Components are supposed to be views only as they have only InvokeAsync and not something like UpdateAsync. So if you'd like to implement any kind of saving logic, you will need to take care of doing this yourself (e.g. via AJAX calls). It is possible (I have verified), but it requires to get familiar with Microsoft.jQuery.Unobtrusive.Ajax and handle responses on the client side in JavaScript (sometimes including things like replacing in JS the DOM element inner HTML with what you get from the server response). You will also need to decide where to put controller actions for view component update endpoints (could be a special Controller class for View Components).

Upvotes: 8

Related Questions