The ViewModel: MVC 2 vs. MVC 3 - asp.net-mvc-2

In my current MVC2 project I implement my MVC by creating a "model" class that gathers data from the database and runs it through business logic, etc. Then I have a "Controller" that gets the processed data from the model and sets the values in a "ViewData" class. This "ViewData" class is a class of getters and setters. This ViewData is then passed to the view in the Controller like this : return View(myViewData);. Finally, in the View, I bring in the data stored in the ViewData by putting this line at the top of my aspx file.
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Core.UI.Web.ViewData.MyViewData>" %>
So, is this the way MVC3 is done? I have a guy on my dev team that is suggesting that the model should be sent, via the Controller, directly to the view like this: return View(myModel);. His reasoning is that this is MVC not M.V.VM.C.
I understand that ViewBag can be used but that just seems like a quick data container.
So, in other words. ViewData or no ViewData?
Thank you,
Aaron

There are certain situations where you might want a view model: to combine data from multiple models/sources, or for specific validation scenarios, etc., but, it's perfectly acceptable to have your view take a model without an intermediary view model, especially if the view model is just a class of getters and setters with no other functionality.
If you're not concerned about exposing methods/properties from your domain model (or if it doesn't apply), I would just pass the model straight to the controller.

In your instance ViewData is just a model - it is a ViewModel and is perfectly fine, and actually the recommended approach in general to use. The reason being you dont want for instance, a primary key from a customer model rendered in the case of a "create customer" function - as a customer id doesnt yet exist. However for editing a customer record, you surely need a key. So - if you use viewmodels in some cases and not in others, not you are inconsistent in your project.
'yes' you can - but I prefer consistency and using a view model gives you the consistency.
You can also use the model - and thats normally how the MVC demos are setup, but unfortunately like most demos, they don't give you what is architectually best, but what is best in whipping together a 5 minute application.

As other have said, although you can get by passing Models to your views, sooner rather than later you'll find yourself wanting to add properties for display purposes only that don't quite belong to the model (e.g. values depending on the current session rather than the model itself.) When you hit that point and it's usually pretty soon you'll be glad you used viewModels.
Technically speaking ASP.NET MVC is not even using MVC but rather Model2. Dino Esposito has a good article about this. Furthermore, on his book Microsoft .NET: Architecting Applications for the Enterprise he even goes as far as saying:
"It is a sharp and bold statement, but we have to make it: today classic MVC is gone. However, some of its variations are healthy and thrive. They are Model2 for the Web and MVP for both Web and Windows. In turn, and only more recently, MVP has undergone a facelift. In July 2006, Martin Fowler proposed to retire MVP entirely and replace it with two variations Passive View (PV) and Supervising Controller (SVC). “
I wrote a review of this chapter on my blog.

Related

Does knockout.js really employ MVVM pattern?

I am new to knockout.js. Few moments back I read the headline features of ko.
I could not understand is ko really MVVVM? Because all they talk about is data binding and the ease of it. But I am sure MVVM is more than data binding isn't it?
Yes, knockout.js does apply the MVVM pattern. It's explained in the documentation:
A model: your application’s stored data. This data represents objects and operations in your business domain (e.g., bank accounts that can perform money transfers) and is independent of any UI. When using KO, you will usually make Ajax calls to some server-side code to read and write this stored model data.
A view model: a pure-code representation of the data and operations on a UI. For example, if you’re implementing a list editor, your view model would be an object holding a list of items, and exposing methods to add and remove items.
Note that this is not the UI itself: it doesn’t have any concept of buttons or display styles. It’s not the persisted data model either - it holds the unsaved data the user is working with. When using KO, your view models are pure JavaScript objects that hold no knowledge of HTML. Keeping the view model abstract in this way lets it stay simple, so you can manage more sophisticated behaviors without getting lost.
A view: a visible, interactive UI representing the state of the view model. It displays information from the view model, sends commands to the view model (e.g., when the user clicks buttons), and updates whenever the state of the view model changes.
When using KO, your view is simply your HTML document with declarative bindings to link it to the view model. Alternatively, you can use templates that generate HTML using data from your view model.
In addition to the answer already provided, there are a few things to keep in mind -
MVVM
Knockout is MVVM because it supports a good separation of concerns. Unlike other JavaScript libraries, such as jQuery, it's goal is to not pollute the view with that which does not concern it.
The view model's purpose is important to understand. It does not attempt to manipulate the DOM because only logic required to serve up data to the view is placed inside of it.
The view's purpose is only to present (render) the data. No logic, validation, or other logic code goes here.
The model is the only place where Knockout can get a bit tricky. It is generally a good accepted practice to place a separate model in your project for Knockout to use, but many developers have found the ease of mixing the model into the view model. The reason for this is obvious (some models are very basic) but again this is only out of ease of implementation.
MVC vs MV*
Surely there are other answers on SO.com that attempt to answer what is MV*, but I wanted to throw my $0.02 in here - Other libraries or frameworks speak to the fact that they are MVC or MVP or MV(whatever) based but Knockout is the only one that I have found that practices what it preaches in this regard. If you have the time and desire look at the structure of other frameworks such as Angular or Ember and you will see there is a blurred line that exists, and more or less they are simply using an MVVM based pattern but calling it something different.
Well I guess it can, however I am working on a project where all styling and UI layout manipulation is done in the knockout js ViewModel file, which is not good practice.

Entity Framework, MVVM, and Calculations Classes

I'm working on a database application that manages industry-specific inputs and then runs that information through somewhat complicated calculations, lookups, etc. to return a series of other values and a go/no-go conclusion.
I've decided to use Entity Framework (code first for provider independence) and WPF (MVVM pattern). I'm using the POCO entities as my data model and the view model is handling the usuals like basic data / business rule validation.
It seems EF + WPF/MVVM are great at displaying and validating input and getting it into the database for querying for your typical business application like a products, customers, orders setup. But it's not at all clear where to plug in a "calculations layer". Between the view models and the data models (my POCOs), things are already feeling a bit bloated, and now I'm facing adding another layer very much like the other two.
Perhaps the best way to approach this is to make the calculations layer a sort of meta-view model and push as much of the validations, change notification, etc. into them and run with lighter actual view models.
Anyone run into a situation like this?
Edit
Turns out what I really needed was to thin the view models and beef up the entities. So I lightened the view models, moved property change notification and basic validation to entities to allow for direct binding, and made calculation classes directly consume entities as well as adding some basic routines to entities. Thanks for the links on thought ADM articles #Peter Porfy.
For moving validation closer to entities, used Fluent Validation (excellent suggestion #Gloopy!). To make it easier to implement property changed notification on entities, adapted this technique. And to avoid having to create endless property wrappers in view model (to set HasChanges property) I used Josh Smith's PropertyObserver.
MVVM stands for Model-View-ViewModel, where the Model layer contains everything what models your actual domain problem.
So it depends on what you mean 'calculation layer'.
Put it where it belongs.
If the actual operation belongs to a domain entity, then you should put that logic into the entity. Don't make anemic domain models:
Article from Martin Fowler about ADM.
DDD works perfectly with EF code-first.
If something doesn't belong to any entity then probably you should expose that as a service. Then use that from your viewmodels through an interface.
A dependency injection container could make your life easier here, but you can live without it.
You aren't plugging another layer because it's the model layer. Your viewmodels should stay as thin as possible, just modelling your view's state and forwarding actual business operations to the entity/service classes.
I'd probably create an interface/object to handle calculations (or several if they can be split up logically) and pass that object in wherever you would want to use it. You might benefit from using a dependency injection framework maybe this post can help with that so you wouldn't have to explicitly instantiate your objects where you need them.
Also this post mentions FluentValidation.NET which may not apply completely but there are likely some good patterns to learn from/use there as well.

getting started with an asp.net webforms UI for c# application which uses nHibernate

Hi
I've been building the backend of my application (using nHibernate for data access).
So far i've had some simple web-services for manipulating my data, but now I'm required to develop a web UI on for my application (using web forms).
I've been looking at some different web frameworks (webformsMVP, spring.net web), and also at some client-side JS frameworks (knockout, angular), and I can't really decide what would be the best for me, and how to integrate it all.
I was hoping to get some insight from you guys.
I think I would like for my general workflow to be something like this:
View is created, calls its presenter.
Presenter contacts business layer to retrieve information (which in turn contacts DAO etc.)
Presenter returns a view-model object, which the view displays.
User manipulates data (maybe using some AJAX to retrieve further needed information)
View sends a view-model of the manipulated data back to presenter
Presenter translates the view-model into a model entity and sends it to business layer
now here are the parts that I find tricky:
A. How to map between view-model and model entities
I think I should use the entitie's ID to retrieve the unchanged entity from the DAO (which actually stores it in nHibernate's 2nd level cache), and perform changes on it.
(another option is to store the entity i'm currently editing in the user's session. but i'm afraid that this kind of caching would create duplicity with nHibernate's cache.)
B. How to translate changes on the view-model into changes on model entities
I'd like to have some logic when changing model entity's properties.
For example, for moving an employee from one department to another, I don't want to allow this-
department1.Employees.Remove(employee);
department2.Employees.Add(employee);
but rather this:
employee.MoveToDepartment(department2);
I'm afraid this could get complicated when translating from a view-model into a model.
Any thoughts on the above two questions, and also about any client-side / server side frameworks would be appriciated.
P.S. some quick background on my app:
-one page of the web app displays the company's structure (departments, divisions etc.) as a tree, and allows the user to click and edit the different nodes, as well as drag-and-drop nodes to change their location.
-another page displays current stock status (for each warehouse- how many products it has, how many machines are currently operative in that warehouse etc.)
- (some more pages which basically display data and allow editing...)
thanks
Jhonny
You can check out Automapper for your entity mapping. Alternatively you can write your own entity mappers and entity updaters. You can then encapsulate the business logic like Move To Department in your entity classes.
Your approach sounds just fine, and I can recommend Webforms.MVP as that is a good framework for writing testable WebForms apps without rolling your own implementation.

Yet Another MVVM question... Is my understanding correct?

Sorry if this is a duplicate, It's not so much 'What is MVVM' though, but rather, 'Is this MVVM', I've read quite a bit, and think I've got a basic understanding of what it is, I've got my own 'one-liner', as such, on how I interpret it, but want to make sure it's correct before I firmly ingrain it in my head,
Essentially; The Model is pure data - no methods, there is one ViewModel per Model, it holds a reference to the Model - it performs all changes to the Models data and finally the View will hold one (or more) ViewModel reference(s) and format & display the data provided by the ViewModel.
(Not after links to tutorials, blogs etc, just a yes, or no with tweaks will be fine, as I'll have to re-read everything again anyway if not :) )
Not completely - at least, not as I would completely define it.
The Model does not have to be pure data. The model is the portion of your application that is completely domain specific, and has no "presentation related" information.
This will typically include all of the domain specific data, but also potentially methods that are pure business logic, and data access, etc. Anything specific to the business logic and processes, and not part of the "display", is part of the model.
Also, although "one ViewModel per Model" is the most common form of working, there are times when you may expose a "model" class through multiple ViewModels. This can be useful, for example, if you are trying to expose only part of a model to your designer, as it allows you to make a smaller ViewModel class. The ViewModel adapts the model for work with the View - if the entire Model is not required, this adapter can be made smaller (and more easily testable, maintainable, etc) by only working with the portion required.
Personally, I prefer to think in terms of "one ViewModel per View", as the ViewModel can adapt one or more models in order to work appropriately with a given View, but even then, sometimes it's helpful to swap out a ViewModel within the same View in order to change content.
Close, but not quite. Here are some points that are are different than yours:
Models can have methods on them. They are not just data. They might have methods like "retrieve", "store", etc. Business logic code. View agnostic.
There is no restriction to how many ViewModels hold a reference to the Model. ViewModels encapsulate view-level behavior, so you may have many different sets of behavior for the same model. For example, one ViewModel might be a read-only transformation of a model item. Another might provide read/write form validation on the same model item.
There can be more than one ViewModel per view, based on the behavior you want. For example, you might include "premium content" behavior with one ViewModel and "free content" behavior with another ViewModel but maintain the same view.
Essentially, yes. Practically, not really. Best practice is always to reduce dependencies and split up your responsibilities among classes on a 1:1 basis, but you'll find IRL situations where it isn't as easy to be a MVC purist.
I think the best attitude is to do your best, then document the rest. Don't sweat purity too much.
There is a lot of great information here, and I think that most of these answers are right. I don't think there is any 1 specific definition, nor is there 1 specific authority on this matter. Even microsoft does not really have clear definition on this.
The one item I would add which is not in the name of MVVM, but is common to all implementations of MVVM that I am familiar with. This is a Messaging or Notification system, which seems to always be linked as a platform for the ViewModel. Messaging just notifies the View Models when things change which may affect others. A good implementation of this in mind allows View Models and Views to both be agnostic about things they do not directly bind to by using generic notification messages.
The benefit of the entire pattern in my opinion is to make you application with modular, swappable parts with as little type-dependency as possible.
This is a real missing part in my mind, as it provides the same benefits / functions that you gain from separate controller logic in the MVC pattern.
That is pretty close. Except it is not correct to say that the Model is only pure data. It can and should contain methods for performing the various use cases against it.
Your understanding is wrong.
You can have several Models and all of them could have their own Views and then be a part of a single ViewModel.
Example:
You have the Models: Product, Customer
Each of them have their own View represented as a Custom Control
And you have a ViewModel which combines all your models and finally on the window of your app you combine all together your Views which talk to your Models via your ViewModel
Think of it like this. The Model is your system, the meat and veg of what the system does. The only considerations it has is how to do it's job, not how it is going to be used. It exposes events, attributes and methods defined at the system level, but it has no concept of what will be pressing it's buttons (or if it even has buttons!). It does not try to format data to a more user friendly format, it formats its data in a model friendly way.
The view model is the UX (user experience). It defines how you are going to use the system. It defines (through public commands and attributes) user orientated access into the system. It is the bridge that the user will use to enter the system. It binds onto the events of the model, and through it's commands, it will provide access into the models functionality.
It should handle validation, (is that age a sensible age?) retrieve data, converting and caching of records whilst they are being displayed. So, for example, you're looking at a patient record, the viewmodel gets the data from the model, and caches it internally, then publishes this to the view. What happens if the model announces an update to that data? Throw the cached data away? what if you've edited it? This is all up to you, and this behavior should be defined in the view model.
The view model is a "contract" of what functionality and data is exposed to the user (through the view). The view model has no concept of HOW it is going to be displayed or interacted with. Commands should be named at a functional level, such as RefreshList, NOT MouseClickHandler.
Finally, the View. This is simply a visible representation of what is in the view model. Buttons and menus etc bind onto commands. Fields bind onto attributes and will update automatically through the magic of binding.
If you ever see yourself doing : "text1.text = value" you're doing it wrong. If you ever find yourself writing a command handler that says "my.ViewModel.SomeCommand" you're doing it wrong.

MVVM - Using simple model as it's own view model is a bad practice?

Guess we have simple model, e.g. let it be a Person { Name, Age }.
Now we want to display a list of persons.
Persons are read-only
We don't need to edit them
We don't need any additional stuff like presentation properties, etc.
Now question is if it is a good practice do not create PersonViewModel class that will probably be a copy of model class or will delegate all its properties? Is it a good idea to simply bind listbox to list of persons, not to their view models? It looks DRY enough, but what about idea of MVVM?
I have no issue with bypassing the VM and using the M directly in the View. Sometimes the models are so small and static that loading them into a wrapping VM is wasteful.
I've created standalone ViewModels, but generally not standalone models. The reason for this is DataBinding -- most POCOs don't implement the INotifyPropertyChanged interface and adding them in to make them pseudo-Models seems to defeat the purpose of re-using a simple class AND respecting the MVVM pattern.
Now, if you KNOW you're never going to be editing them, it may not be a bad idea. A VM with simple property redirects seems a bit pointless to me.
As far as I'm concerned, if you implement INotifyPropertyChanged, then it becomes a ViewModel, and you can bind to it. :) When I wrote SoapBox Core which is all MVVM, I took the approach that everything is a ViewModel. The only Model objects were classes from third party libraries that I brought in and wrapped in a ViewModel of my own.
I wouldn’t create a ViewModel for the Person business object when the ViewModel doesn’t introduce new required functionality.
You might be interested that there is a second approach in the MVVM community: Create a ViewModel per View and not per Business Object.
Sample applications that follow this approach can be found on the WPF Application Framework (WAF) website.