I'm working in ASP.NET MVC, but this question is pretty much applicable to any MVC framework (and maybe even others).
In a typical MVC application a request arrives at the controller, which then prepares a model object and then calls the view, passing the model object as a parameter. The view then uses the data in the model to generate a response to the original request. Any data in thew model object can be freely used by the view, but I'm wondering - is it OK for a view to request data from elsewhere, like a direct call to a service or something?
At the first moment the answer seems to be a clear "no, why would you need that? Just add everything the view needs to the model object". But I did arrive at this question while working on a practical project, so here's my situation that causes me doubt:
The view needs a lot of data to be able to display itself. Most notably, there is the data of the actual form fields, and also data for all the dropdowns that are on the form (lists of potential values for different fields).
On the other hand, in my project the views are themeable. That is, different customers (our customers, who have bought our website and use it in their business) will have the views customized to suit their needs. Different customers need different fields displayed, and sometimes the data sources for the same dropdown can differ significantly as well.
One possible way would be to query all possible data on every request and add it all to the model object. But there will be a significant performance penalty for this. Better if only the necessary data was queried, however the controller doesn't know what the view will need.
So I see 2 options:
- Allow the view to call external functions that return the value lists for the dropdowns;
- In the model object, add delegates (or actually add methods to the model object) which will perform the query when the view asks it to.
Neither approach seems very elegant to me. Are there any other alternatives, or if not, which one is better and why?