ASP.NET MVC - Models notifying the Views? - asp.net-mvc

In some of the classic descriptions of MVC, the Model notifies Views via the observer pattern. It seems to me that this doesn't happen with ASP.NET MVC, and so one of the fundamental relationships between Model, View, and Controller is missing.
Is this the case? If so, why?

Views in ASP.NET MVC are Stateless. They exist for a very short time and then are sent down to the client.
The process goes something like this:
Request comes in to the Controller.
Controller retrieves the Model and instantiates the View (passing it the Model).
The View is rendered, the markup returned to the client, and then disposed of.
Therefore, since the View no longer exists after it is sent to the client...there's nothing to notify about Model changes.

Observer pattern is not needed. In the original definition of View it says:
A view is attached to its model (or
model part) and gets the data
necessary for the presentation from
the model by asking questions.
http://heim.ifi.uio.no/~trygver/2007/MVC_Originals.pdf
In the context of a web app, the only View possible is markup (HTML/XML) rendered by a browser. So, as in ASP.NET MVC, the View code is handed a Model instance that it can access to provide information to the user.

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.

MVC, difference between controller and model?

I was watching some Swift instructional videos from Stanford on youtube. The instructor (Paul Hagerty, great teacher!) speaks about how iOS is built around the idea of MVC (model-view-controller). I've read some people say on stack overflow that the idea is dead, and others say that a lot of web developers use this terminology now.
I'm having trouble differentiating between controller and model. I've read MVC described as user interface (web page/UI), controller (server), and model (database). But the instructor described it as view (UI, which is easy to understand), model (data and logic that does a calculation for example), and controller (which connects model and view with your specific programming logic).
What I don't understand is if there is no database in the case of a standalone application (not web), aren't we also creating the data and logic of how our program works at the same time? What is the difference between controller and model in this situation?
At the risk of being crucified for over-simplification: you can think of MVC as a way to separate "concerns" - in English - each has it's own "responsibility" (separation of concerns).
So in your "simple example" you could "separate" the concepts as a client and a server - risking even more shame, a browser and some web site.
controller: The browser takes user input and makes a request to;
model: A web site that responds with some data which could simply be a HTML document
view: The browser renders that data to user
So:
The browser doesn't "know" how the data was created/built, it just manages the request/response and displays the result
All the web site does is build some data and give it (back) to the requester. It doesn't care how it's used/rendered/displayed/filtered etc.
All the view does is render/display data in some meaningful way to the user. It doesn't care where the data came from, nor how it was built.
Hth.
The model is the data. Imagine a table view controller. The view is the table view. The controller is the UITableViewController. The model can be as simple as an array of strings.
The controller mediates between the model and the view. It picks the data that it wants to display and installs it in the view.
For a really simple view controller that just shows some text, the model could be as simple as a string. If the text is static, a view controller might not even have a true, separate model. It would just display the text that's baked into the storyboard.

Why does the View know about the Model?

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).

MVVM ViewModel vs. MVC ViewModel

ViewModel is a term that is used in both MVVM (Model-View-ViewModel) and the recommended implementation for ASP.NET MVC. Researching "ViewModel" can be confusing given that each pattern uses the same term.
What are the main differences between the MVC ViewModel and MVVM ViewModel? For example, I believe the MVVM ViewModel is more rich, given the lack of a Controller. Is this true?
A rather challenging question to answer succinctly, but I'll attempt it. (Bear in mind that the answers to these kinds of questions are still the subject of debate amongst developers.)
In MVC, the ViewModel provides all the information necessary for a View to be rendered. The data it contains is created using data defined in the Model. The View reads the ViewModel and renders the output. Input from the View is passed to the Controller, which manipulates the Model, constructs an appropriate ViewModel, and passes this to the View for rendering.
In MVVM, the ViewModel serves the same function as it does in MVC, but it also replaces part of the MVC Controller by providing commands which allow the View to manipulate the Model. WPF databinding manages the updating of the View according to changes in the ViewModel (and this effectively replaces the remaining function of the MVC Controller).
It's been a while since I played UI Design Patterns Bingo.. however let me take a stab at this..
MVVM is just something that MS has come up with... because it helps you to get the most out of WPF. You combine the state and behavior of the view into a class (a presentation model) that is easily testable + then you use data-binding to get the data into any view.
This link has a brief of the evolution of MVVM. Combine this with Fowler's "GUI Architectures" series, and you should be on your way.
Update: Didn't know there was something called MVC-VM. Apparently a brainchild of the ASP.NET MVC crowd. Looks and sounds similar to MVVM (except tuned for ASP.NET MVC); the only difference is that it places a restriction that there is 1:1 mapping between VM and View. I'd have guessed 1:N, but everything else matches.
I know this is a (way) old question, but I've been pointed to it as an example of using "View Model" in the context of MVC. I argue that this is incorrect and can lead to confusion by people who are new to either/or/both patterns. Whoever is doing it--stahp. Here's why (and it's even an answer to the original question in a roundabout way).
An example of when this happens can be seen in this question. The user is trying to use a View Model that implements INotifyPropertyChanged in an ASP.NET MVC application, thus mashing together desktop and stateless web application design in an architectural fail and heartbreak.
To put it simply, there is no "View Model" in the MVC pattern. There is, however, a functional equivalent, and that's the Controller. Just to be clear about the parts and their purpouses,
MVVM (desktop applications):
Model - Strongly typed object that holds data to be passed between the View and View Model
View - The UI viewed by the user and through which the user interacts with the system
View Model - Interprets user actions (e.g., via ICommand), performs them, updates application state
MVC (web applications):
Model - Strongly typed* object that holds data to be passed between the View and View Model
View - A UI generator that combines the Model, code and HTML to render a webpage
Controller - Accepts user requests, interprets them, updates application state and uses a View to convert this state into an HTML webpage
The Model is practically the same in both patterns. Desktop models may implement update event notifications, web Models may be dynamic (i.e., not strongly typed), and both may or may not include validation methods or metadata.
The View in the desktop is what the user sees. In the web, it is a generator that outputs HTML for browsers to display on the client side. It must interpret user interaction on the desktop, but on the web that is handled by client side javascript, the browser, and the requests that are sent back to the server.
The View Model/Controller are roughly functionally equivalent, but differ greatly in how they are implemented and how they operate. In the View Model, user interaction with the application is transferred to View Models via ICommands, routed events, and other methods (many MVVM frameworks provide different ways to hook View Models to the UI and other parts of the application). In a Controller, a request comes in with all information needed for the Controller to return a result to the user (assuming it's a 200 OK request). The Controller must perform whatever work is necessary to create the state (aka Model) needed for the HTML generator (the View) to create the response. Design-wise, the Controller sits above the View and Model knowing and controlling both, whereas the ViewModel sits next to the View, passing the Model (and other information) between them.
What really seems to confuse some people is that there are client side MVVM frameworks that you can mix into your MVC application. These exist solely in javascript in the user's browser, and have nothing to do with whatever particular pattern you're following on the server side. You can run a classic ASP website that uses MVVM on the client side. Hell, you can run static HTML pages that use MVVM on the client side. They are that separate.
These javascript MVVM frameworks typically follow a similar pattern to the desktop MVVM pattern described above, but adjusted to work more in tune with the nature of the HTML DOM and javascript. For example, there is no extensive binding system woven into the DOM, and javascript has a very limited type system, so matching up templates to models is much different than in WPF. They also typically work disconnected from the server, and when they need to interact, prefer AJAX calls rather than POSTing the page back to the Controller (AJAX calls typically are handled by WebAPI Controllers in ASP.NET MVC).
So, to summarize, there really isn't a View Model in MVC. The Controller is the rough equivalent, but is very different in how it receives user input, interprets it, and returns a result to the user. Using the term "View Model" to refer to anything in MVC can only lead to confusion, and therefore should be avoided. Use the proper terms for the proper parts of the pattern. It may seem pedantic, but it should help keep things clear and be less confusing to people who are new to both patterns.

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.

Resources