Nested ViewComponent, is it possible?
Asked Answered
G

1

6

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

Grubstake answered 8/3, 2017 at 21:1 Comment(3)
Is it possible to have nested View Components? Yes. Simply include the appropriate reference to the inner View Component (Component.InvokeAsync()) from within the view of the parent View Component as if you were doing that from a page.Lightface
Is it better to have independent View Components... or Partial Views? That's a subjective question that will probably yield opinions, not answers.Lightface
Thank you very much Bob. I can understand that there is no correct or wrong way here but I would like see pros and cons of both ways in this particular scenario.Grubstake
W
8

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).

Weizmann answered 29/5, 2018 at 19:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.