tags:

views:

37

answers:

1

Using the MVC pattern in a desktop application, what's a good approach to introducing a view to its respective controller, and vice-versa? E.g., should you use constructor injection to give the view its controller, then have the view call a setView method on the controller and pass itself as the argument?

(Question isn't specific to any framework/platform.)

+3  A: 

Views should be as dumb as possible. They shouldn't know about, or rely on having specific controllers instantiate them. At best they should have access to some kind of base controller class reference that is handed to them upon construction, usually as part of the "view data" object which wraps the Model to be used as well.

Your controller should be responsible for instantiating the view, giving the view the model it will be displaying, and returning the view's result. The view shouldn't be calling back into the controller to tell it what to return, as this gives control of the logical flow to the View, which isn't really MVC-like.

womp
Thanks! About the first part, when would you want to give the view the base controller class reference, rather than just the model?
fig
You would give it both. Depending on your implementation, it wouldn't be *required* to give it a controller reference, but generally the controller would have access to the initial request data, which your view might need. For example in ASP.Net MVC, each View gets passed a model, but there is also a well-known structure called "ViewData" which holds a "ControllerContext" object, which you can access if your view needs to poke around at request data.
womp