While I'm reading the book "ASP.NET MVC 4" I'm wondering about MVVM. I started googling and cannot find any books about developing web applications using MVVM, so I must be missing a bit of information here.
From what I understand, MVVM is used in web applications on the client side via knockout.js and other frameworks.
If however I was to develop a Windows Phone application, I could use MVVM directly without using MVC.
Does that mean, the concept of MVVM / data binding just does not apply to client-server web applications?
MVVM is really sort of a subpattern. There's not really any "MVVM" web app frameworks out there. They're all MVC and you pretty much just incorporate a view model if you want one.
With ASP.NET MVC, in particular, you just create a class, generally with a name in the form of [Model Name]ViewModel or [Model Name]VM. That class will have only the properties from your model that you'll need to work with and anything extra that doesn't make sense to put on your actual database-backed model, like SelectLists, etc.
In your action, you just pass an instance of this view model to your view instead of your model:
return View(viewModelInstance);
And, of course, make sure your view accepts that:
#model Namespace.To.MyViewModel
The only slightly complicated part is wiring the view model to the model (i.e., getting data to/from the view model/model. You can do this manually by explicitly mapping the properties, or you can use something like AutoMapper.
MVVM is the standard design pattern for WPF/Silverlight development, and should not be confused with MVC for ASP.Net development.
The two may sound similar and share some common parts, but they are two different design patterns.
From what I learned about knockout.js, it was designed to create "data bindings" similar to what you would use in WPF/Silverlight development, which is why the MVVM design pattern applies there.
To quote from another answer of mine regarding the differences between MVVM and MVC
In MVVM, your code classes (ViewModels) are your application, while your Views are just a pretty user-friendly interface that sits on top of the application code and allows users to interact with it. This means the ViewModels have a huge job, because they are your application, and are responsible for everything from application flow to business logic.
With MVC, your Views are your application, while your Controller handles application flow. Application logic is typically found in ViewModels, which are considered part of the M in MVC (sidenote: the M in MVC cannot be considered the same as the M in MVVM because MVC's M layer contains more functionality than MVVM's M layer). A user is given a screen (View), they interact with it then submit something to the Controller, and the Controller decides who does what with the data and returns a new View to the user.
MVC is a one-way data-binding system.
Fill your Model in Controller, then pass it to View.
MVVM is a two-way data-binding one.
Fill your Model, use it in View, when the View state's changes, your Model update automatically.(Vice-versa)
Does that mean, the concept of MVVM / data binding just does not apply to client-server web applications?
No, you can apply the MVVM pattern to client-server web applications.
In fact Asp.Net MVC actually kind of does use this pattern - when the controller creates the view, it can pass in a "view-model". This view-model is often a POCO data object with all the data that a particular view needs, drawn from the model (database). The view uses this data to render the html page.
MVVM on wikipedia says it was introduced by Microsoft with WPF. Specifically, the view binds to properties on the view-model. The view-model then maps this to the database. By this definition then, Asp.Net does not exactly match that. Client-side frameworks like knockout.js and vue.js do support this kind of 2-way binding with view-model properties.
All these patterns are based on the fantastic MV* pattern. It was originally called the MVC design pattern. So this is the exact same pattern as Asp.Net MVC then? Actually, not quite. Controller means something completely different to start with (see MVC on wikipedia). The original MVC controller handles all user input directly not via the view. Second, the original MVC pattern was designed for a desktop app GUI and Asp.Net MVC adapted the pattern for use in a client-server web app. An ASP.Net controller is a collection of http end-points which the client-side html page can hit (eg form-post, page-navigation, ajax).
So there are a lot of M-something-V patterns and the general pattern is often called the MVC design pattern.
There's one more important wrinkle: client-side vs server-side. We've introduced rich client-side javascript frameworks and the fantastic MV* pattern is great here too. So now we could have something like: client-side View-Model-ServerHTTPEndPoints and server-side ServerHTTPEndPoints-ServerModel. The server-endpoints refers to Asp.Net controllers or the equivalent in whatever web framework or programming language you are using. From the server-side point of view, the entire client-side html is the view. The client-side model talks to the server ajax api (http endpoints) to sync data or trigger advanced actions. The ServerModel is normally a database. In knockout/vue, instead of client-side "Model", it would be ViewModel. If you use react/vue with redux/flux then the client-side would be View-ViewModel-Model-ServerHTTPEndPoints where the Model would be the redux/flux Stores. Also, often on the server-side, a service is introduced: ServerHTTPEndPoints-Service-Model. This way unit tests can hit the service directly rather than firing up the entire web server and making HTTP connections.
I have used MVVM in desktop applications and I have a property in my viewmodels named Model where I store a business object as the model. My views have a property named DataContext where the viewmodels are stored before the views are loaded. A view bind its controls to the business object using the path DataContext.Model.BusObjPropertyName. I have a UserInteractionService that register from the start the relationships between views and viewmodels. When a viewmodel needs to show another viewmodel, it calls the method ShowView in the UserInteractionService and pass the viewmodel as parameter. Then the service instantiate the view corresponding to the viewmodel received, set its DataContext property with the viewmodel and show it.
If it is possible to do the bindings to a path like that above in Asp, all this model can be reused either in desktop as in Web applications.
Related
I have a query regarding MVVM and MVC. I am developing an Desktop Client and Web application. I intend to use WPF (and MVVM) to develop desktop client and ASP.Net MVC for web app.
I have never used ASP.Net MVC before although I have never truly liked Web Forms (except some features like Master Page, output Cache etc.) and I mostly use AJAX (jQuery), and handlers to populate HTML and processing inputs (I think I was close to MVC after reading about the pattern but in a different way).
Now these applications will mostly have same inputs, reports, and database. I am planning to create Model that can be re-used in MVVM and MVC both. But after reading various articles on these pattern, and analysis of ASP.Net MVC Code, I doubt that it could be done. In MVVM, View never knows Model while in MVC, Controller shares Model with View. Also, in ASP.Net MVC, a View (ASPX file) is derived from System.Web.Mvc.ViewPage and the labels/captions are populated from Model itself.
Is there a way I can use same Model for both applications?
Thank you.
Ritesh
In MVVM, View never knows Model while in MVC, Controller shares Model with View.
Not quite right. In MVVM the view is bound to a view model. Exactly the same as in ASP.NET MVC. In ASP.NET MVC a Controller doesn't share a Model with the View. It shares a View Model. It talks to the Model and then builds a View Model that is passed to the View.
Contrary to MVC in MVVM the View could talk to the Model but this happens indirectly throughout the View Model, so neither the View nor the Model know about each other's existence.
So you could perfectly fine have the same Models in both your Desktop client application and in your web application. The only difference will be the view models.
Moving from the traditional way of architecting web applications with a Business Layer, Service Layer, Data Access Layer and a Presentation Layer to the MVC design pattern, I find it difficult to understand how it fits in the old model.
It seems to be that the MVC model itself already has done allot of the separation of concerns that is needed and used to be achieved via a layered architecture. Can someone shed some light on this subject please?
As a reference, below is how I understand it, please share your view on this
MVC Views and Controllers along with View Models -are- Presentation Layer
MVC Models - could be - Data Access Layer or Business Layer or even Service Layer
I see the Asp.Net MVC part only as the view (or presentation) part of the whole application.
I struggled too with the problem how to structure the app in a proper way.
Following the Onion Architecture I heard about here (and especially the image found here), my solution looks this way:
Project.Core
Business logic/services implementations, entities, interfaces that must be implemented by the other projects (i.e. "IRepository", "IAuthenticationService",...)
Project.Data
DB connection - in my case NHibernate repositories and entity-mappings go here.
Implements data-interfaces of Project.Core
Project.UI.Web
The Asp.Net MVC ("presentation") project - it wires the whole app together.
Has implementations for Interfaces in Project.Core and wires them (and those from Project.Data) up with some DI framework like Castle Windsor.
Project.UI.Web follows the following conventions:
its models are only(!) viewmodels
the views consume their own viewmodel (one-view-one-viewmodel)
the controllers just need to validate the input, transforms it into domain objects (as the business logic knows exacly nothing about viewmodels) and delegate the real work (business logic) to the business services.
Summary:
If you follow this model it's helpful to focus on Project.Core: that is the real application. It doesn't worry about the real persistence of data nor cares about how does it get presented. It's just about "how-to-do-it". But it's laying out the rules and contracts (interfaces) the other projects must provide implementations for.
I hope this helps you with how to layout an Asp.Net MVC application!
Lg
warappa
As others have said, it doesn't change much. My apps are typically architected as such:
Model Layer (Domain and View Models)
Repository Layer (data access)
Service Layer (sometimes implemented
as WCF services depending on the
app/requirements)
Server side MVC
Layer (Asp.net MVC itself)
Client side MVVM or MVC (via
either Knockout.js, Backbone.js, or
Spine.js)
In the server side MVC layer, my controller methods are very light. They typically call a method on a service layer object to get some data and pass it along to the client as Json data.
Because I'm sending Json back, my views are also very light and sparse. Typically just containing script includes and templates which will be rendered with a client side templating library.
In short: nothing much changes.
I'm only familiar with a few presentation patterns: MVP (Model, View, Presenter, common in windows forms/asp.net), MVC (Model, View, Controller) and MVVM (Model, View, View Model, commonly used in WPF/Silverlight).
Link: http://haacked.com/archive/2008/06/16/everything-you-wanted-to-know-about-mvc-and-mvp-but.aspx
Above link should answer some (if not all) of your questions.
The way I usually write ASP.NET MVC applications is by including at least a Service/Business layer hybrid for CRUD operations (because data access belongs neither on the view model or controller and definitely not in the view!).
Very basic explanation:
If you create a new MVC application you will automatically get a Controllers, Models and Views folder.
Your controllers act like your Business Layer
Models are Data Access/Service layer
and Views are the presentation layer.
See http://www.asp.net/mvc for a fully detailed explanation.
ASP.NET also has UI, Event Handling and if good logic layer is implemented then the BLogic layer too. So that can we say its Model View Control style. Or its not that ?
No. ASP.NET Web Forms is an implementation of Page Controller pattern.
Chapter of Fowler's PoEAA about the Page Controller on Google Books
As a pattern MVC is more concerned with the idea that the controller orachastrates the view and the model.
In Web Forms there is no controller. The View and the code behind (closest thing to a controller) are inherently the same thing, there is no separation of concerns.
Also depending on how you go about it, the model part of the MVC isn't necessarily your business logic. For us its literally a View Model, and contains data relevant to the specific view only. Business logic is handled in autonomous components.
With traditional web forms, I generally see the code behind (which is really part of the UI) having intimate knowledge of either business logic or data base access (and often a mixture of both).
Due to code behind it is hard to get away from this.
In my mind web forms create tightly coupled UI and business logic, and don't provide an easy way to enforce separation of concerns.
I'd say web forms does not adhere to the MVC pattern.
In MVC, all requests are routed to a Controller.
In ASP.NET all requests are routed to a Page. That is a View and not Controller.
ASP.NET better matches with MVP rather than MVC. Reason being, in MVP, a View is supposed to process user inputs/requests and pass it on to appropriate Presenters.
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.
What are the basic differences between classic .cs-aspx.cs-aspx (code behind/beside) model and new MVC model?
The basic difference between MVC and classic ASP is that in classic ASP all of the code and mark-up for the application exists in the .asp file. In MVC the .aspx file contains only the code and mark-up for rendering the page. The rest of the application for handling requests, retrieving model data, and enforcing business logic exists in controller and model classes. These classes can be much more easily tested than class ASP code because it is separated from the code that is responsible for rendering the view.
This separation of concerns is the basis of the MVC pattern. According to the pattern, the code is divided into three major components -- Model, View, and Controller. Classes in the model represent the business objects for the application, the persistence framework, and business logic applied to the business objects. Classes in the controller accept incoming requests, use the inputs or query parameters to retrieve the appropriate model data, and generate the necessary data for the view to render. Views (aspx pages) take the data supplied by the controller and generate the mark up.
Webforms (codebehind) is somewhere between classic ASP and the MVC pattern. Webforms does not enforce the separation of concerns in the way that MVC does, but it does allow much more of the code to exist "behind" the actual page. For example, you can separate out the business objects, business logic, and persistence framework (the Model, if you will) from the code that is responsible for generating the view. The difficulty is that the controller actions (input handling and model retrieval) are still linked with the view rendering code. This integration makes it much more difficult to test this code and makes the view/controller code much more dependent on each other than is necessary -- the concerns are "mixed", not "separated." In general, this is evidence of bad design because it make it more difficult to make needed changes in the future.
Hope this helps.
Simply put it this way: MVC is how really web apps should be built. Code-behind (asp.net web forms) is not a good practice. If you are truly a developer you will appreciate that the MVC is the best practice since it really separates logic from data and presentation. Simply MVC is the elegant and right way.
A really simple way to perceive the difference between MVC and ASP (or ASP.NET forms for that matter) is that in MVC the Controller is the handler of the request.
Requests get routed to a controller not a 'page' or a 'form'. The controller will pass along info in the request to the model then make some simple choices as to which view that should be used to present the desired state of the model. Note this is the important point the controller has a choice of what view to use in the response.
MVC breaks the relationship between the requested URL and the UI code needed to render a particular representation of data.