Why does the View know about the Model? - asp.net-mvc

I have done some work on ASP.NET MVC 3 but I'm no expert.
So, based on the pattern definition, the view has no direct awareness of the model and does not communicate with the model directly; only controller is directly dealing with model.
However, in ASP.NET MVC 3, I can access the model data directly from the view using Razor engine. Isn't that breaking the pattern design or am I missing something?

the view has no direct awareness of the model and do not communicate with the model directly
Not exactly. Exactly how to interpret this statement might depend on the reader.
I've read quite a bit on model-view-controller and asp.net-mvc and I find similar statements scattered around and so the way it's worded can be a bit confusing.
A view knows what the model is. That is, it should know what the model type is, what the model contains or by some means know how to use the model to display what is necessary.
If we have a page called UserProfile then the view knows that it should display the user's name, email address, age and favourite website.
The view might be told to expect a UserProfileViewModel. Such a class would contain exactly the properties that the view needs so that it can easily display them.
What is better to say is that the view should not modify the model. In fact, the view should not do much of anything. Views are supposed to be stupid - they aren't for processing business rules, modifying data, connecting to databases, and so on. They just display stuff.

The model contains the data, the controller manipulates the data and the view displays the data (model). The view therefore is the interaction with the user.
The view must know what to show, so it has the model (with its data) to do so. It never manipulates directly, but sends information to the controller which in turn will manipulate the data.

I guess you have mistaken the concept of MVC. MVC does not say that "View is not aware of Model". In practice, each view is tightly coupled with a model (unless view is coupled to dynamic model or base type).
MVC is actually separation of concerns.
Controller decides the business rule and decides what data to be shown to user.
Then it populates the Model.
Then pass on the Model to View. (Think of it like passing on some data to be displayed on view).
Now View is not aware how model is created and validation rules of model.
Model is not aware which view will consume it. There can be many views coupled to a model.
Controller is not aware of model validation or what property of model is being displayed on view.
And MVC is just a pattern to follow, it does not stop you from writing business logic inside view or make db calls from view.

Refer to this article to read about the three different types of "models" introduced by ASP.NET MVC.
What it sounds like you are referring to is the view model. This model is simply a container or a way provide structure around the data that the view is responsible for displaying. It is simply a data-transfer object (does not have any behavior).

Related

Does adding business logic in a view model in asp.net increase the size of the object being passed to the view?

This is something I've been trying to find definitive answers on and have found no luck online thus far. If in an ASP.NET project I have a view model that I'm using to pass data to the view in the browser, does including methods for accessing the model layer to fetch data increase the actual size of the resulting object being passed? My intuition is saying yes and I've been trying to read through other answers on stack overflow to find a solid answer to support it, but have had no luck.
The view model has some truly monolithic methods in it, some of them spanning 100+ lines or more going through LINQ operations to filter enumerable lists of data.
Nope, it shouldn't. A view is (typically) built from your Razor .cshtml and sent to the user. Only the contents of your view (the layout, bundled JS, stylesheets, page itself, etc) are sent to the user. The ViewModel is only used in building the view.
MVC has a concept called model binding, which is where incoming HTTP request's data is mapped to an appropriate set of parameters. On a request a new ViewModel will be created and passed to the appropriate Action method (or if the request can be mapped to a set of parameters, that also happens; doesn't have to be a single parameter).
On a side note, having a complicated ViewModel can make model binding hard. And having business logic in the ViewModel is also frowned upon; that makes it harder to reuse and follow. It's ideal to move it out into your business layer, or barring that into your controller.

What should own the model in an MVC pattern?

Let's say that I'm drawing a solar system inside of a single SolarSystemView (a subclass of UIView). Should my SolarSystemView have an instance variable of class SolarSystem (a class containing a data structure with all of the important planetary and stelar properties), or should that be under ownership of an instance of a SolarSystemViewController? Or is it something completely different? I can't find any example code that gives a satisfactory answer.
I imagine that if the view owned the model, operations would be very smooth, but that also doesn't feel like good style. After all, the SolarSystem instance has to change dynamically somehow, and with the same or similar rate that the SolarSystemView updates.
In the MVC paradigm, the Model is supposed to be separated from the View. To get the data it needs to draw itself, it asks the Controller for it, which in turn asks the Model for it. That way, we decouple the information from the GUI. Think of it as Model Controller View if it helps. Therefore, in most cases, the Controller "owns" the Model.
For example, in cs193p, the CalculatorViewController (Controller) has a CalculatorBrain (Model) property, which it interacts with to get the results of equations to display in the View.
In your particular example, the SolarSystemViewController would probably have a strong reference to the SolarSystem, which it would poll for data that it would hand off the the SolarSystemView so that it could draw itself when it needed updating. The SolarSystemView might also notify the SolarSystemViewController when the user interacts with it so that it can display other views or update the SolarSystem, among any other tasks it could perform.
Note that the MVC paradigm in Cocoa and Cocoa Touch is a little different than the more generalized version of MVC seen elsewere, like Smalltalk. For example, if you look at the Wikipedia page on MVC the diagram there should look different than what you've been learning. In fact, GoF (Design Patterns) describes MVC thusly.
MVC consists of three kinds of objects. The Model is the application
object, the View is its screen presentation, and the Controller
defines the way the user interface reacts to user input. Before MVC,
user interface designs tended to lump these objects together. MVC
decouples them to increase flexibility and reuse. MVC decouples views
and models by establishing a subscribe/notify protocol between them. A
view must ensure that its appearance reflects the state of the model.
Whenever the model's data changes, the model notifies views that
depend on it. In response, each view gets an opportunity to update
itself. This approach lets you attach multiple views to a model to
provide different presentations. You can also create new views for a
model without rewriting it.
In both these cases, the Model itself is contacting the View to update it. However, on iOS, interaction between the Model and the View are handled through the Controller. This is well explained in the first session of cs193p as well as Apple's own documentation on MVC relationships. That way, you only need to rewrite the Controller code to reuse the Models and Views elsewhere.
Here's the MVC diagram from cs193p to clarify.
In this case, SolarSystemView should not contain any instant of the SolarSystem class. The SolarSystemViewController should be the go between your view (SolarSystemView) and the model (SolarSystem).

Why should I use view models?

I'm new to developing web apps using ASP.NET MVC. In fact, I'm rather new to developing web apps, regardless of technology.
Currently, I'm working on a project just to get to know the ASP.NET MVC framework better. When reading on SO and elsewhere on the internet, the consensus seems to be that the views should never deal directly with the business objects (i.e. objects implementing business logic and containing associated attributes). Instead, view models should be used. However, this introduces a couple of issues:
Where do I put my validation code?
I need to add code to map between business objects and view models.
In fact, it seems rather cumbersome and I haven't really seen anyone explaining properly why it's a bad idea passing business objects to the views. Could someone please try to explain this (or point to a good explanation)?
Just a clarification; I'm not looking for examples on how to handle the two issues with view models above but simply an explanation on why I should use view models at all.
Where do I put my validation code?
On the view models you should validate everything that's specific to the application like for example the date should be in en-US format culture, ....
I need to add code to map between business objects and view models.
That's why there are tools such as AutoMapper.
Different problems arise when you use directly your domain models in the views:
The views have specific requirements for displaying the data (localization/globalization) so you either end up with spaghetti code in your views or you put this code on your models so that they become less reusable in other applications because you have polluted them with specific presentation stuff
You have different validation requirements based on the view. Let's take for example the case of Add and Update views. In the Add view the Id property won't be needed and it won't be required because you will be inserting a new item. In the Update view the Id property would be required because you would be updating an existing item. It would be difficult to handle those specific validation rules without view models.
The models might contain properties such as IsAdmin and then I am leaving to your imagination the implication of a controller action with the following signature:
[HttpPost]
public ActionResult CreateUser(BusinessObjectUser user) { ... }
assuming that you have hidden this property from the underlying form by not including it.
The business models don't change often whereas the UI could change more often. What if your customer asks you to split your screen in two? The way you present the information changes and the way it is formatted also change. If you use your models directly into the views the spaghetiness of your views becomes worse and worse with every change.
About 60% of the question I am answering on StackOverflow in the asp.net-mvc tag wouldn't have been asked if the OP have used a view model.
Three reasons to why you should use View Models:
Reason 1: Remove logic from your Views
Reason two: Security
Reason three: Loose coupling
Below link may useful:
http://www.codeproject.com/Articles/223547/Three-reasons-to-why-you-should-use-view-models
First off, allowing the Views to have direct access to the Business Objects in ASP.NET MVC introduces some extra security concerns. ASP.NET MVC does a lot of Model binding for you when a user posts a value back to your controller. This can open you up to various kinds of attacks. By introducing a View Model in between, you can be sure that only the fields you are interesting are bound (because the ViewModel will only contain the fields you care about).
As for the other questions:
Where do I put my validation code?
I use DataAnnotations on my ViewModels directly. That allows me to use the Model validation architecture built in to ASP.NET MVC. If there's any validation beyond that I handle it in my controller.
I need to add code to map between
business objects and view models.
True. But using something like AutoMapper can greatly reduce the amount of boilerplate code that you have to write by hand.
MVC is easy to understand and has very little overhead. But those that have used the Model-View-Controller pattern for some time know that it isn't perfect. Not even close. The Model-View-ViewModel pattern offers an interesting alternative.
It is important to understand that the Model-View-ViewModel pattern extends the Model-View-Controller pattern. It isn't a dramatic paradigm shift if you are used to MVC. Even though the advantages of MVVM are subtle, they are profound.
What are some of the advantages MVVM has over MVC?
Better Separation of Concerns
Improved Testability
Transparent Communication

Is there any dependency between view and a model?

Normally in the MVC Pattern, when a user clicks on a page the request would be sent ,then controller would handle the request ,then process it using the model and route it to the appropriate view.
I have read the post about the passive model and active model,but is there a possibility where the view directly interacts with the model, would that be a bi-directional relationship (i.e Model<->View) or one-directional (i.e Model->View).
Is it appropriate to have a relationship between Model and View? Well in a ASP.NET MVC project should i have a relationship between model and view, or have it independent of the model?
I think it's almost always preferable to have your views be model-specific, that is, strongly-typed. Where models share related data, you can reuse partial views that are specific to that subset of data. In ASP.NET MVC, your model is -- or should be -- ignorant of the view since they only way they can interact is through a web request, which is a controller function. No you may say that you could interact through web services, but I would consider those to just be another flavor of controller. In fact, with MVC, I see very little need to develop a separate web service at all, using REST-based controller actions instead.
I always see the View as the way to present the Model. According to this point of view, the View is Model aware and in ASP.NET MVC you should inherit pages from ViewPage to avoid abusing from ViewData or castings.
With that in mind, the Model is not view aware and is just an object that is used from the view to present data to the user.
Finally, you can share the same Model from different Views, for example an XML output can share the same model as the HTML output but the views can be very different.
The cycle is more or less, Controller generates Model, passes it to the View, that shows de Model and in case there's interaction, posts the input to the Controller and the cycle starts again.
In Java Swing MVC is implemented as the View and Controller combined, with a View that both reads from the model and registers for events from it which effectively makes them loosely dependent on each other.
Usually web applications don't do this as the real view is rendered on the client and can't receive events from the model as easily, so in those cases the relationship only goes one way. Its certainly not a bad thing to have a relationship between the model and the view as long as the Model does not dependent directly on and view classes. In that case a dependency cycle would be set up and that harms maintenance and especially testing.
For example the way this is achieved in Swing is via a Listener interface, which the view can then implement/provide an implementation of to the model.

What's the difference between a ViewModel and Controller?

What are the responsibilities of one vs the other?
What kind of logic should go in one vs the other?
Which one hits services and databases?
How do I decide if my code should go in the viewmodel or the controller?
For the record, I am using ASP MVC, but since the question is architectural, I do not believe it matters what language or framework I am using. I'm inviting all MVC to respond
The ViewModel is a Pattern used to handle the presentation logic and state of the View and the controller is one of the fundamentals parts of any MVC framework, it responds to any http request and orchestrates all the subsequent actions until the http response.
The ViewModel Pattern: More info
In the ViewModel pattern, the UI and
any UI logic are encapsulated in a
View. The View observes a ViewModel
which encapsulates presentation logic
and state. The ViewModel in turn
interacts with the Model and acts as
an intermediary between it and the
View.
View <-> ViewModel <-> Model
The Controllers (Comes from the Front Controller Pattern): More Info
It "provides a centralized entry point
for handling requests."
HTTP Request -> Controller -> (Model,View)
--Plain Differences:--
While the ViewModel is an optional
pattern the Controller is a must, if
you are going the MVC way.
The ViewModel encapsulates
presentation logic and state, The
Controller orchestrates all the
Application Flow.
The ViewModel can be on the client side as well as server side.
Wherever it may be, the sole purpose of viewmodel is to play the
presentation data.
In MVC architecture Viewmodel is not mandatory but with out controller the request from the client cannot be processed.
Controller can be visualised as the main interface between client and server to get any response from the server. It processes the client request, fetches data from repository and then prepares the view data. Viewmodel can be visualised as view data processor/presenter thus an interface to manage the view more eloquently.
In the overall context of a web application we can say the controller is the application request handler whereas viewmodel is only the UI handler.
The Model-View-Controller (MVC) is an architectural design pattern which exists, primarily, to separate business logic from the presentation. Basically, you don't want your back-end touching your front. It typically looks like this:
The reasons for doing this is because, by separating the back-end and the front, you don't tie your user-interface directly to your data/work. This allows you to put new interfaces onto your business logic without affecting said logic. In addition, it also improves the ease of testing.
A simple example of where MVC comes in handy - let's say you have an application that manages your company's finances. Now, if you are correctly using MVC, you can have a front end that sits at some financier's desk and lets him handle transactions, manage the finances, etc. BUT, because the business logic is separate, you can also provide a front-end to your CEO's Blackberry that lets him see the current status of the business. Because the two front-ends are different, they can do different things while still providing (different types of) access to the data.
EDIT:
Since you updated your question a bit, I'll update my answer. There is no perfect science to the separation of MVC. There are some good rules of thumb, however. For example, if you are talking about GUI components, that is probably a view. (Are you talking about look and feel, usability, etc.) If you are talking about data and the "business" side of the house (databases, logic, etc), you are probably referring to a model. And, anything that controls the interaction between the two is most likely a controller.
In addition, it should be noted that, while Views and Models are typically "physically" separated, a controller can exist with a view when it makes sense.
You are correct when you say the framework (or even language) for MVC doesn't matter. The pattern itself is language agnostic and really describes a way to architect your system.
Hope that helps!
I think there's some value to learning received doctrine. But there is also value in understanding how the doctrine came to be the way it is.
Trygve Reenskaug is widely credited with inventing MVC. N. Alex Rupp's article Beyond MVC: A new look at the servelet architecture includes a History of MVC. In a section on Reenskaug's 1978 work at Xerox Palo Alto Research Center, there's a link to his paper Thing-Model-View-Editor: an Example from a planningsystem. There the pieces are described like this.
Thing
Something that is of interest to the user. It could be concrete, like a house or an integrated
circuit. It could be abstract, like a new idea or opinions about a paper. It could be a whole,
like a computer, or a part, like a circuit element.
Model
A Model is an active representation of an abstraction in the form of data in a computing
system
View
To any given Model there is attached one or more Views, each View being capable of
showing one or more pictorial representations of the Model on the screen and on hardcopy. A
View is also able to perform such operations upon the Model that is reasonabely associated
with that View.
Editor
An Editor is an interface between a user and one or more views. It provides the user with a suitable command system, for example in the form of menus that may change dynamically
according to the current context. It provides the Views with the necessary coordination and
command messages.
Rupp identifies Reenskaug's Editor as a Controller or Tool.
MVC Triads emerged in SmallTalk-80. The model was an abstraction of the real-world concept, the view was its visual representation, and the controller was the buttons and slider bars that allowed the user to interact with it (thereby "controlling" the view). All pieces in the triad were interconnected and could communicate with the other two pieces, so there was no layering or abstraction involved. Since then, Reenskaug has "preferred to use the term Tool rather then Controller." According to his notes, these are the terms he has used in later implementations
Some logic and model should be invoked to generate some data (structured or semi-structured). From this data the returned page/JSON/etc. is created, typically with only rudimentary outlining logic.
The first part (creating the data) is done by the controller (via the model usually). The second part - by the View. The ViewModel is the data structure being passed between controller and view, and usually contains only accessors.
Model represents your data and how it's manipulated. Thus, model touches the DB.
View is your UI.
Controler is the glue between them.
MVC stands for Model, View, Controller.
Model = Data (Database tables)
View = HTML, CSS, JavaScript, etc
Controller = Main logic, a contract between Model & View.
In simple and graspable terms,
MVC allows you to develop your applications in a way that your business data and presentation data are separated. With this, a developer and designer can work independently on a MVC app without their work clashing. MVC makes your app avail OOP too.

Resources