MVC - Who formats the model? - model-view-controller

Before rendering into a view model should be formatted:
multilingual data localized;
date, time values formatted;
numbers formatted.
Who performs all this formatting - Controller or View?
Am I right that all the formatting is performed by the Controller which creates so called ViewModel containing only formatted values and sends this ViewModel to the View?
Thanks in advance!

Eric Petroelje is right, but I would build helper a class(es) to get localised content/dates etc, because localisation isn't always in the views, e.g. sending emails with localised content. I would have something like LocalisationHelper.GetString("MyKey"), or LocalisationHelper.GetDate(Date.Now), where the LocalisationHelper knows the users current locale (maybe from Session).
Then use this directly in the views where possible:
<%= Html.Encode(LocalisationHelper.GetDate(Date.Now)) %>

Design Patterns 101.
Model is for storing data (usually database-backed).
View is for presenting the data (not manipulating it).
Controller is for manipulating the model and passing that to the view (choosing the right locale for instance would go here).
MVC doesn't necessarily mean you have 3 distinct classes, but rather 3 components or layers. These are abstract and don't necessarily have to be tied to one physical class. Inside your Controller layer, that can consist of any number of helper classes or whatever.
I agree with part of what cartoonfox is saying, everything is intertwined. For instance, if you develop a view for a shopping cart, but the model is containing birthday information, then it isn't going to work. It is simply a design pattern to help remove duplication of effort. When you have fewer variables and less noise, it is much easier to focus on what needs to be done and understand it very well.
I had a discussion with our team about using annotations to render forms on a web page. These annotations were placed in the model or entity class. You will often work directly with entity classes, so it eliminates quite a bit of overhead and duplication of effort if you put your annotations here. Because your annotations are placed directly on the model class, you cannot end up with a view for birthday information, it just isn't possible. In addition, by following patterns, you strip out the junk that doesn't add value to the end result. You simply write the business logic and close to nothing else.
Although the annotations were in the same class as the model layer, the presentation or view layer consisted of the annotations and the helper classes. It doesn't need to necessarily be distinct classes or boundaries.
Another example would be. I've worked on some PHP web "applications" in the past. I use applications because they were a monolithic block of code, more or less a single main method with all the logic in there (which is hardly a functional application).
If you don't abstract code into functions and simply use a single method, you will end up with a lot of duplication of effort. If you tried to understand that monolithic code block, you would be in for a heap of trouble (as was I, it was hard to learn what was going on, then I would find a similar block of code somewhere else and be dumbfounded why a few things were tweaked the way they were).
It can be done any way you want, but design patterns such as MVC help you simplify what you write in order to get it to work as well as more easily wrap your head around the solution. Another popular design pattern or approach is divide and conquer.
To answer your original questions:
In Java, localized data would be done transparently by the application. For instance, if you wanted US English locale support, you would create a properties file:
messages_en-US.properties
and then place all your US English content in there. Depending on how much content this may be, you might want to use a different approach.
For my application I have whole pages in a different language so what I do is this. My controller determines the client's locale or a best match. Then it chooses which view to display and passes the model (data) to the view.
If you need dynamic formatting for your date/times, then your controller is responsible for determining which one will be used. Then, your view is responsible for using that converter to format the value.
I'm using JBoss Seam so the MVC design pattern is still used, but more abstractly. I don't have actual 'controllers', but an interceptor which is responsible for handling a specific piece of functionality (determining the client's locale, then another for their date/time preference). My controllers that would be the equivalent of a Spring Controller are action components responsible for handling page actions.
Walter

The view is responsible for this not the controller.
To explain I need to elaborate a bit about what the "view" is:
In both web-based and traditional GUI MVC patterns, the View is responsible for the external representation of whatever parts of the model that are shown. If that means "formatting" data from the model then so be it.
The controller shouldn't format the data - because the controller is responsible for doing things to the model based on events/commands coming in from the outside world. The controller doesn't have anything to do with rendering the output.
Example:
I want to display a shopping cart with several order lines:
Adding things to the cart causes the controller to change what's in the cart model.
Changing my locale causes the controller to change a setting in the user model to indicate preferred locale.
Whenever the cart is displayed, the view has to ask the model for the order lines and decide how to display that - maybe doing locale-sensitive work.
The same customer could ask to see the shopping cart in multiple different currencies. That just means changing what it looks like in the view. It's still the same shopping cart for the same customer with the same things in it.
If this is a web-app made from web template pages, you might embed code to pull in localized messages e.g. <%= message_renderer.text(:insufficient_funds) %>. In this case the "message_renderer" and the template file are both part of the view.
Views aren't necessarily just web-based templates. In some Java-based frameworks for example, we put "view objects" into a velocity template. Those view objects are linked back to objects in the model, but they also perform on-demand rendering and formatting behaviour. Those are part of the view although they're not just a template.
It's a bit confusing with frameworks like ruby on rails and groovy on grails where they call the template the "view" - when a view is really more than just a template. Traditionally (in Smalltalk MVC and in Java's Swing) views are just code that can perform formatting, rendering and any other display-related behaviour.

All that stuff seems like presentation layer logic, so personally I think it should go in the view.
ETA:
I wouldn't advocate for having the view call service layer objects in the general sense, but for localization I think it makes sense.
For example, lets say you have lots of static text on your pages that you have tokenized and stored in a database in various localized forms. I don't think it would make sense for the controller to have to lookup and put all those text tokens in the model. Even though a text token lookup is technically a "service layer" operation, I still think it makes sense for the view to call that service directly via some utility class rather than having the controller do it.

Related

What's the controller in MVC pattern and why does it exist?

While working with Unity, I realized that separating Model and View would make my code more readable and straightforward. Constructing the whole model, all I had to do is just create some UI and bind it to Model.
But I still don't understand what 'Controller' is, and why does it exist. I don't think I had trouble when I directly bound View to Model, not through Controller.
So the question is if we can bind View to Model directly, why do we need Controller? What's the benefit of having Controller between Model and View?
At the highest level the Controller is the link between the View (displaying the UI/UX) and the Model (creating and managing your database and its tables).
True, it is possible to write code without any Controller usage but your Views will quickly get very cluttered and each file will be full of logic that is much more nicely stored somewhere else hint hint.
The Controller (and Model and some other places such as helpers) is thus the perfect place to sort out all the back-end code so that all you need to do is send a single field or object to your View to display.
An example is somewhat painful because by its nature the Controller is where you go to sort out your code as things get more complicated but this is a great article to get you on the right track! HTH
https://www.toptal.com/unity-unity3d/unity-with-mvc-how-to-level-up-your-game-development
I don't have years of experience, but in my understanding controllers provide a bridge across view and models. While view contain the pretty part and models contain useful parts the controller do the calls of functions passing values from database to view or inputs to model. That provide a way to avoid lots of injection like class A calling class B, calling class C, etc.
You can put rule business in controllers or in view, but thats not the expected in MVC architecture. The first important thing (for me) in software programming is readability, whats MVC provide.
if you've interest, search for other architectures like MVVM, to compare then.

Where does language translation fit in the MVC pattern?

I'm building a multi-lingual web application using the MVC pattern as the starting position. The application has a number of forms that users will be interacting with and many of these forms will have fields that do a lookup from a database table, 'Province' for example.
If I need the options in these lists to be displayed in the users' language on the screen, I can see a couple of ways to do this:
In the model. When querying the model, I can provide the language that I desire the results to be returned in. This would allow translations to be used everywhere that data from the model is displayed without changes. However, this also means that the Province model in my example (plus all other application models) now need to know how to do language translations.
In the controller. I can query the model in the controller action as usual and then create a 'Translator' object that I can pass the results into before completing the action. This would imply that each controller action would potentially be duplicating the same translation code, violating the DRY principle.
In the view. Since the presentation of the application is generally expected to exist in the views, and the language of the user doesn't impact the business logic of the system, an argument could be made that language translations belong here. Especially considering that a page could also contain static content that will need to be translated. The downside to this is that it would complicate the views somewhat, especially for the front-end designers who will have to work around the new translation code.
Is there an accepted best-practice for where text translations belong in the MCV pattern for web applications? Does this change at all if I were to be loading the select list options via an AJAX call instead of at page load time?
Thanks for the help!
The best place to handle it is in the view. Your question only references dynamic data from the database, but you also have to handle the static information in your views as well. Best to handle both of those in the same place. A common practice in MVC for handling multiple language is resource strings, separate views for each language, or a combination of both. For information from the database resource strings would work well. You would store a token in the database for the options in the list (that token could be the English translation) and the view would get the appropriate translation from a resource for the specified country/locale. There is a good detailed explanation on this approach in this blog post.
If you need to translate part of your UI, then I would create a helper method that would read a resource file and output a translated string for that resources. E.g.
#Translate("NewUserHeading")
So regarding the UI, it makes sense to handle this in the UI.
If the data that you are going to translate at some point might be shown in a Flash client, or a mobile app, then it should be translated by a server and it should have nothing to do with your MVC application.
Honestly, any interaction with a database should be handled in the model, and that's the only thing handled in the model. Interpreting/organizing that data should be handled in the controller. I guess more information would be need as to where this translation is coming from and how that works to really give a solid answer.
The view will just display strings from a resource file. Including the correct resource file for the locale should do it. In Web applications, it's often a single language JS file defining the UI strings per locale, e.g, strings.en-us.js, strings.pt-br.js and so on.
Some strings do come from the server dynamically, the controller doesn't need to know about it, the model should just grab the localized strings and return is as part of the data request.
So it's either in the view (if it's static) or in the model, (if it's dynamic). Controllers should just translate data from the view to the model and from the model to the view
Another very important thing to consider is WHEN to Translate. Using a once-per-each-translation method like #Translate("NewUserHeading") is fine if you only have 100 translations on your page, but what if you have more?
Because think about it, translation is based upon language choice and that only happens once-per-page or even once-per-session. The way that the Kendo UI people do it in their demo is that way, when the User clicks a new language a new set of server files is loaded. That would mean having something like:
/src/html/en-us/
/src/js/en-us/
/src/html/es/
/src/js/es/
etc..
Check it out at https://demos.telerik.com/kendo-ui/grid/localization
It's a trade off of more work for better performance. The ultimate use-case of translation right now is https://www.jw.org/ with over 900 languages!

What is the advantage of Model-View-Controller (MVC) over Model-View?

Could anyone give an example of why it would be advantageous to use MVC instead of a simpler Model and a View only.
Note: whether it's called MVC or MVP (Model-View-Presenter), I'm talking about the one where the View receives input, then the Controller will respond to the input event by interpreting the input into some action to be done by the Model. When the model changes, the View will update itself by responding to events from the model.
What is disadvantageous of simply letting the Model respond to events in the View and vice versa?
In MVC, if I changed the model in a way that affects the controller then I'll have to do changes in the controller. In Model-View, if I change the Model, I'll have to update the view.
So, it seems like we are introducing complexity by adding the "controller" part?
In MVC, the Model is blind to its environment, the view can be too - passing off (blindly) its events to the controller, which knows more about the view and model. So when all is said and done, the controller is the 'non-reusable' disposable part of the system, since it is the most context aware component.
if I changed the model in a way that affects the controller...
The the model should expose simple CRUD methods in such a way that those using the methods do not have to know anything about the passed update object, nor what really happens inside the model.
This means that the view, IMO, has to do a bit of work by creating the passed record, since Controllers are supposed to be stateless and the view is more persistent. Controllers get triggered and 'kick-in' do their work with a passed object and do not have a state.
The passed data is created by some sort of generic convention.
Let me go even further. Suppose you have a view, a tablegrid, and a control whose enabled property is dependent on item is selected in the grid -- you COULD create a view that handles both those controls and this logic internally, and that would probably be the way to go in such a simplified example.
But the more atomic your views are, the more reusable they become, so you create a view for every, yes every, control. Now you are looking at a situation where views have to know about each other in order to register themselves for the right notification...
This is where the controller steps in, since we want to stick all these dependencies onto him, the long term disposable one. So the controller manages this type of view-to-view notification scheme.
Now your views are ignorant as they can be and independent, thus reusable.
You can code a view without having to know about the system, or the 'business logic' as they like to call it. You can code a model without having to know too much about your goals (though it does help to tweak the model to enable it to return the datasets you have in mind).... but controllers, they are last and you have to have the previous two firmed up before you can wire things together.
Here is another thing to think about -- just as the Model is supposed to abstract-away and provide a generic interface to the underlying implementation of the data it is managing (the client does not know if the data comes from a DB, a file, a program setting, etc) -- the view should also abstract away the control it is using.
So, ultimately this means a view should not (caveat below) have functions/properties that look like this:
public property BackgroundColor{get;set}
Nor
public function ScrollBy(x,y){}
But instead:
public SetProp(string name, object val){}
And
public DoCmd(string name, object val){}
This is a bit contrived, and remember I said ultimately... and you ask why is this a good idea?
With reusability in mind, consider that you may one day want to port things from WinForms to, say, Flex, or simple want to use a new-fangled control library that may not expose the same abilities.
I say 'port' here, but that is really not the goal, we are not concerned with porting THIS particular app, but having the underlying MVC elements generic enough to be carried across to a new flavor -- internally, leaving a consistent and ability-independent external interface intact.
If you didn't do this, then when your new flavor comes along, all your hard references to view properties in the (potentially reusable/refactorable/extendable) controllers have to be mucked with.
This is not to mean that such generic setters and cmds have to be the interface for all your views abilities, but rather they should handle 'edge case' properties as well as the normal props/cmds you can expose in the traditional hard-link way. Think of it as an 'extended properties' handler.
That way, (contrived again), suppose you are building on a framework where your buttons no longer have buttonIcon property. Thats cool because you had the foresight to create a button view interface where buttonIcon is an extended property, and inside the view your conditional code does a no-op now when it receives the set/get.
In summary, I am trying to say that the coding goals of MVC should be to give the Model and View generic interfaces to their underlying components, so when you are coding a Controller you don't have to think to hard about who you are controlling. And while the Controllers are being (seemingly unfairly) set up to be the sacrificial lamb in the long run of re-usability -- this does not mean ALL your controllers are destined for death.
They are hopefully small, since a lot of their 'thinking' has been shoved off into semi-intelligent Models and Views and other controllers (ex: Controller to Sort a Grid or Manipulate a TreeView) -- so being small they can be easily looked at and qualified for reuse in your next project -- or cloned and tweaked to become suitable.
It actually reduces complexity by separating the workflow logic from the domain logic. It also makes it easier to write unit tests and makes your application easier to maintain and extend.
Imagine if you wanted to add a new data type. With the approach above, you would probably duplicate a lot of the workflow logic in the new class as it would be likely to be tightly coupled to the domain logic.
The discipline involved in separating the workflow logic into the controller makes it more likely that you will have fewer dependencies between workflow and domain logic. Adding a new data type would then be more simple, you create the new domain object and see how much of the controller you can reuse, e.g. by inherited from a controller super class.
It would also make it easier to change frameworks in future - the model would probably not change too much and so would be more portable.
Having said that, you might want to look into MVVM depending on what you are using as your presentation layer: Benefits of MVVM over MVC
Advantages of MVC/P (I am talking about Supervising Controller here) over MV include:
You can handle complex data binding code in the controller, if required.
You can test that complex presentation logic without a UI testing framework.
You can also have a graphic designer make your views, and not see your code, and not mess up your code when they fix your views.

Why is MVC so popular?

I was originally going to make this a longer question, but I feel like the shorter I make it, the better you'll understand what I mean.
The MVC architectural pattern has 3 dependencies. The View depends on the model. The Controller depends on the View and Model. The Model is independent.
The Layers architectural pattern defines N - 1 dependencies, where N is the number of Layers.
Given three Layers: Model, View, and Controller, there are only 2 dependencies, as opposed to 3 with traditional MVC. The structure looks like this:
View ---> Controller ---> Model
[View depends on Controller, Controller depends on Model]
It seems to me that this style accomplishes the same goals and produces looser coupling. Why isn't this style more common? Does it truly accomplish the same goals?
Edit: Not ASP.NET MVC, just the pattern.
With regard to griegs's post:
As far as mocking, Layers still allows you to use the Command Processor pattern to simulate button clicks, as well as any other range of events.
UI changes are still very easy, perhaps even easier. In MVC, the Controller and View tend to mesh together. Layers creates a strict separation. Both Layers are black boxes, free to vary independently in implementation.
The Controller has 0 dependencies on the View. The View can be written, and time can still be saved with loose coupling.
Because you decouple the interface from the controller making changes easier.
Also consider the scenario where you need to get started on a project but the artwork won't be ready for weeks or months. Do you wait or do you write all the code required for the pages and simply then wire up the view to the controller.
At least that's what we did and we saved months.
Also it made UI changes easier to cope with because there wasn't any code in our aspx pages that did anything.
Our tests were also better as we could mock up anything including button clicks etc.
And if you're talking about the asp.net-mvc framework, there is no code in the aspx files and no viewstate etc.
In proper MVC the controller doesn't depend on the view afaik. Or maybe I'm not understanding it correctly.
The model defines the data.
The view defines what the output looks like.
And the controller is a translator from a model-understood grammar to view-understood grammar.
So essentially the controller is independent. The view is independent. And the model is independent.
Yes? No?
I'll be bold, and try to explain why your method didn't catch on.
The MVC pattern basically requires the view and model layers to agree on an API.
Since one serves the other and there are no dependencies inside the code it leaves the controller to behave generically, all it needs to do is take a certain structure in the view layer and call the matching API on the model layer.
You'll note that agreeing on an API between the view and model isn't really such a big deal it has to happen anyway. And what you get is good separation between back-end front-end development.
In your proposed solution a lot of development is required on the controller side. The controller will be required to understand all the elements in the view and to map them to the specific calls required on the model layer.
Since the controller is a single access point connecting many views to many models this can quickly get out of hand and end up being an incomprehensible controller module.
Look at some Struts2 examples to see what I mean...
I think I'm understanding your point:
Yes you can make the View only depend on the Controller only by making the Controller transform (using PHP as an example) the Model objects to non-Model objects like simple arrays.
As we already know, performing this transformation can be more effort than it's worth if the decoupling isn't actually needed. If the View uses the Model objects then it has this dependency. However, this can be relieved a bit by having the View depend solely on the Controller for its required input, which can be Model objects.
The Symfony PHP framework promotes this style of skinny controller shuffling between Model and View. You can still directly call upon the Model layer to retrieve objects within the View layer but it's strongly urged against for the coupling issues you bring up. Within the View you can call include_component() which actually goes back up to the Controller if you need to query the Model.
I haven't gotten back to this in a long time, mostly because I was still thinking. I was unsatisfied with the answers I received, they didn't really answer my question.
A professor, recently, did steer me in the right direction. Essentially, he told me this: Layers which separate Model, View, and Controller is MVC. In the vanilla MVC architectural pattern, the dependency between the View to the Model is often not used, and you effectively end up with Layers. The idea is the same, the naming is just poor.
Choosing a presentation pattern for a new or enterprise web development on the Microsoft platform is a daunting task, in my opinion there are only three; View Model, Model-View-Presenter (MVP) or ASP.NET MVC (a Model2 derivative).
You can read the full article here ASP.NET MVC Patterns
I'd like to add some more things. First of all for my point of view is we use the model as container for the information we want to pass and show on the view. Usually the action method into the controller ends with return view("viewName",model).The view itself probabily will change its layour against the model :
on the view :
if(model.something==true) {
%>
somethign to show
<%
}
At this poinf the definition of model is hard to find.
I can say (especially on enterprise conext) the are two "model"
one is the domain model/entity model or how you want to call it that wraps the data coming from the lower layers (database,etc) and the view-model who contain the information we wants to show plus any other information we need to hide/show portion of interface
The controller orchestrate the the views and is indipendent from the view but a bit dipendent from the model:
into the controller
pulic actionResult Index(){
....
if(model.BoolProperty==true){
return ("firstView);
}
else
{
return ("secondView");
}
}
I hope it makes sense
In my opinion ,you'd better try it in your programme , you can use ruby on rails ,or codeigniter( for php ),these great framework may be helpful to your understanding the MVC.

What should not be inside an MVC view?

From the limited amount of people that I've talked to regarding MVC web frameworks, I've heard people say that, forgetting about forms, a view file should ideally contain HTML markup, string manipulation and a few for each loops. I've also been told that if statements in views should be avoided if at all possible. Is this generally agreed?
EDIT:
The situation that has inspired this question is writing a navigation, I'm finding myself writing:
if secondary_navigation_item has children
...
I'm thinking, ideally, does this qualify as logic (that should not be here)?
Generally speaking, the View should not contain any server-side business logic. But it can still contain logic that directly pertains to rendering the view.
An example would be a view containing some sort of variant record, whose display depends on the setting of a particular field. For example, a record that displays different information depending on a sex field being set to male or female. Which, of course, would require an if statement.
To say that your views should not contain any conditional logic is just silly. How else would you generate UI elements like "new message" icons or flash messages—use a different view template for every possible interface state? It's like saying that your controller should not contain any variable assignments because data manipulation belongs in the model.
It's perfectly alright to have logic in your view as long as it's view-related logic. You shouldn't get caught up in absolutes or pedantic interpretations of the model-view-controller definitions. As long as you understand and apply the underlying concepts of MVC, you're on the right track.
Every rule has an exception, and there are cases where you would do string manipulating in a controller or even implement application flow in the view. Sometimes you just have to evaluate it on a case-by-case basis and apply a little common sense.
A view should basically contain:
HTML Markup
Javascript
CSS
Minimum of server-side code you may need to put into view
So, a View should typically contain the layout elements. The main processing logic should go in Controller.
More Info:
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

Resources