Reputation: 8891
I have an MVC application and I typically have the controller pass everything needed by the view. But when my views are nested inside of other views it's a pain to have to forward these variables on to the nested view.
Is that just how it is, or should I allow my partials/fragments nested inside my views retrieve data from the Model?
As an example, I have a list of states that I use in several nested partials/fragments. I have to pass this list through my views every time I want to use them only on nested partials/fragments in those views. Seems like it's prone to error and it feels not very DRY.
Upvotes: 3
Views: 345
Reputation: 5263
If you are concerned about speed performance of your app, and you want to make it more straightforward, I would say you allow views to read data from the model (read only). It is more complicated when both controllers and view must be in sync re. data that views need and controllers should provide to views. And when views can access model directly, you don't need to verify that controllers provide this data.
In regards to the argument that MVC concept is based on loose coupling, there is no contradiction as Model is still independent and does not rely on views or controllers. And the difference between controllers and views are that controllers can both push and pull to (from) the model, and views can only pull from the model.
Upvotes: 0
Reputation: 608
Split main applogic on several small MVC "widgets"(controllers), where every "widget" has own relation to Model and own separate View. Then, during execution aplication you can just execute widgets in runtime, and pass to main template "READY widget views".
Something like that is described here: http://en.wikipedia.org/wiki/Presentation-abstraction-control
advantages:
Upvotes: 0
Reputation: 22238
It is perfectly valid for View to directly read from the Model.
Look at wikipedia article or at a picture by Martin Fowler: http://martinfowler.com/eaaCatalog/modelViewController.html
Upvotes: 3
Reputation: 72961
The View should never have direct access to the Model. In fact, the whole point of the MVC paradigm is that each component is loosely coupled with the other. So you can swap our your Models or Views easily. You can't do that if you put Model code in your View.
Helpers or other modules tend to ease the pain in these situations. I would suggest looking into those. There is also the concept of "Fat Models, Skinny Controllers", putting more in your Model so it is easier to access data shared across multiple Controllers.
In the end, it's up to you. MVC lines can get blurred. However, IMO, accessing the Model directly from the View violates the core concepts.
Upvotes: 3