MVC Architecture – Should the Controller Pass Data to a View in the MVC Pattern?

Architecturemvc

I work with ASP.NET MVC (and other web-based MVC implementations) quite often, but this is something I've never been sure of: Should controller and view communicate?

Of course the controller should be choosing which view to use, but what I mean is should the controller be passing data to the view? In my opinion, if the view is expecting data from the controller, then they're effectively tied together as a (controller, view) pair. Instead, I usually have the view communicate with the model itself and be independent of any controller.

Do I have the right approach, or is this a case of there being no one correct answer? Does the answer change when working in the web versus other environments? Does the answer change when you have the concept of a strongly-typed view (like in ASP.NET MVC) or not?

Best Answer

The controller prepares data which will further be passed to the view for rendering / displaying. It also accepts user input data through a publish-subscribe mechanism or similar. Check out the first diagram on Wikipedia or Martin Fowler's website for more information about MVC.

if the view is expecting data from the controller, then they're effectively tied together as a (controller, view) pair.

While a view generally accepts data, in most MVC frameworks, it does not depend on specific controllers. Exceptions are, for instance, the JavaServer Faces family. Generally speaking, frameworks like Rails, Django or Spring MVC allow you to decouple views from controllers by passing data (the context, commonly a map/dictionary/bag) to a view (where a view is an implementation of the template view pattern).

Does the answer change when you have the concept of a strongly-typed view (like in ASP.NET MVC) or not?

Whether or not your programming language is strongly-typed has no influence on the way your are organizing your application.