difference between models and view models - asp.net-mvc

I have been researching asp.net MVC project structure's for a new project and have a question about something is confusing me. What is the difference between models and view models? Would I be correct in saying that view models encompass models in the form properties?

I've a blog where I want to display the list of the latest posts, latest comments, post categories in a single view. How I can do that? I can strongly type my view to any one of the model right? There comes view model.
I created a view model called BlogViewModel that contains latest posts, latest comments and other stuff as properties and I bind my view with this model. The posts, comments.. are domain models while the BlogViewModel is the view model I created specially for the view.
Tomorrow I'll show my blog in a mobile version and at that time I may create a simple view model that contains only less properties. Finally.. view models are for views and most of the times they acts as wrappers over the real domain models!

A model is usually more closely related to how your data is stored (database, services, etc.) and the model will closely resemble those.
The ViewModel on the other hand is closely related to how your data is presented to the user. It is usually a flatten version of your model, denormalized, etc. It can be the aggregation of multiple models.
For your typical Person objects, your model may contain properties like the following:
FirstName
LastName
BirthDate
However, in your ViewModel you may choose to represent it differently and have something more like:
FullName
Age

ViewModel is the version of a Model from the business-domain layers adjusted to the specific View.
It has only Properties relevant to the view and shouldn't have methods(except simple ones like ToString()).
ViewModel is a "data container" only.

A model is simply a representation of an object in your application. However, there are a few different types of models that you should be aware of.
Domain Model: This represents a domain object in your application, like a SQL table if you are using an ORM (Linq2SQL, EF).
View Model: This represents an object that you want your end users to view/edit/etc. A view model could contain properties from several or no domain models and typically exclude properties that your end users should not be mucking with. View Models should only contain the elements that are needed to display the appropriate data to the end user for a specific request.
Here is some Jimmy Bogard for you about View Models and their use.

Related

How to create persistence , domain and view models

I have been reading a lot about the importance of keeping layers separately and the concepts are mind blowing :) . However,I looked into many places to find a practical example on how to separate these three types of models and had no luck. How do I connect them together in a practical situation? Here are few questions I have
My understanding is that persistence models contain the POCOs that we use to create entities , domain models contain the business logic and view models are used to expose relevant data. Am I correct?
If I am correct , how do I actually connect these different layers in a single solution. I mean at the end of the day , they are classes and how do I connect domain class(model) with a relevant persistence (model) and the view model?
Can someone please point me to a great tutorial that teaches how to build n-tire asp.net applications?
If not, and if possible can someone tell me how to build and connect three types of models for the following scenario.
A Customer has a Name , DOB , Address and a collection of Orders
An Order has a Customer, Date , Price and a Description
How do I create separate persistence, domain and view models(eg: A view model to display all information about customer except DOB and all orders related to the customer )
More importantly how do I connect them?
Thanks heaps!
Cheers!
you create viewmodels to match the view, not every property from the model (Entity) you might want to show in the Create/Edit view, or you want to show it but combined or in a different way, that's why you need viewmodels, usually you would have a property in the viewmodel for each editor/input in the view
for example in the Entity you can have one DateTime property but in the ViewModel 2 properties one for Date and one for Time,
or in the Entity you will have property of type Country but in the ViewModel of type int (the value of the id)
and when you have this separation you need to map Entities to ViewModels and the other way around
for demo app you can look here: http://prodinner.codeplex.com/

Scope of viewmodels in asp.net MVC 3

I have read online that it is bad practice to use a "kitchen sink" model:
Rule #3 – The View dictates the design of the ViewModel. Only what is
required to render a View is passed in with the ViewModel.
If a Customer object has fifty properties, but one component only
shows their name, then we create a custom ViewModel type with only
those two properties.
Jimmy Bogard's subsequent explanation of how this is good, however, left me a little questioning. It'd be so easy to have my Model just contain a list of Customers, I could even use my POCO's.
So now I get to create custom little view model fragments for every page on the site? Every page that uses a Customer property would get one, but of course could not be shared since some of the information is extraneous, if one page used Age but not Name, for example. Two new mini view model classes right?
This is very time consuming, and seems like it'll lead to a million little custom view models - can someone elaborate as to the utility of this approach and why the easier approach is bad?
View model class can be used not only to transfer values, but it also defines data types (data annotations), validation rules and relations different then ones used in model. Some advantages that come to my mind right now:
There are different validation rules when you change user's password,
change his basic data or his subscription setting. It can be
complicated to define all these rules in one model class. It looks
much better and cleaner when different view models are used.
Using view model can also give you performance advantages. If you
want to display user list, you can define view model with id and name
only and use index to retrieve it from database. If you retrieved
whole objects and pass it to view, you transfer more data from
database than you need to.
You can define display, and editor templates for view models and reuse them on different pages using html helpers. It looks much worse, when you define templates for model POCOs.
If you would use your POCO objects as view models, you would essentially be showing your private objects and break the encapsulation. This in turn would make your model hard to change without altering the corresponding views.
Your data objects may contain details that are appropriate only to the data access layer. If you expose those things to the view, someone might alter those values that you did not expect to be altered and cause bugs.
Many of the same reasons as for having private members in OO languages apply to this reasoning. That being said, it's still very often broken because it's a lot of extra work to create all these "throw-away" models that only gets used once. There exists frameworks for creating these sorts of models, though the name eludes me, that can tie objects together and pick out the interesting properties only which takes away some of the drudgery from creating specific view models.
Your View Model tells the View how data should be shown. It expresses the model. I don't think its necessary to have two view models unless you have two ways to express your model. Just because you have two pages, doesn't mean you will be showing the data any different way, so I wouldn't waste time making two mini View Models when it can be in one reusable view model, Imagine if later you have a page that needs Name and Age, you would create another view model? It's absolutely silly. However, if you had two pages both showing 'Age' and it needed to be shown in a different way, then I would create another one.

EF4 models and MVC models and view models ... To model or not model?

I'm currently working with EF4 and asp.net mvc 3 and I'm certainly having some trouble working through the different types of models that are possible when you bring these technologies together.
I have a database that I've defined and through EF4 I have a model of my database. But there is also the model that gets passed to my view and what about view models???
Lets say I have a mvc model of a project. This project has description, name and category properties. I have a view page that creates a project and returns it back to the controller for insertion into the database through ef4. So I initially created a class with those exact properties to be my model. However my page also requires a list of categories to choose from when creating that project, so I added a string array to my model which got passed to the page along with the other properties as part of my project model and it worked fine. Everything is great ... but I got to thinking ... because if the project model models a project then it shouldn't have a complete list of categories. It should only have the category that is part of that project.
But where does this complete list of categories go. In the view bag? This seems incorrect to me? Should I be creating a view model? How would this view model look? How about adding a method to the project model that would be something along the lines of GetCategories() then I could call this method from the view page ... but does that break the separation of concerns ideal in mvc?
I'm sure many people will have different views on the subject but any commentary that will help me wade through this mess will help.
Thanks,
In all the but simplest applications you're best off not passing Model objects to Views. A View should have a ViewModel which is constructed by a Controller using data from Model objects and which contains everything that View needs to display its information.
ViewModels decouple your presentation layer from your business layer, and your example demonstrates why this is important; your View needs information about a Project, but also a complete list of all Categories that Project could belong to - such a list does not logically fit into the Project domain model object, but fits perfectly logically into a ProjectViewModel.

Bestpractice - Mixing View Model with Domain Model

Is it reasonable to mix view models with domain models?
So i.e. the view model object contains some domain model objects (not the other way around!)
Generally, you will have to reference your Domain Models in your View Models, or at least load the Domain Models in the controllers and pass the information on to your View Model.
I prefer to keep Controllers and Views as simple/dumb as possible, because both Domain Models and View Models are FAR easier to test.
So, I often reference my Domain Models inside my View Models. Sometimes I use aggregation, sometimes I just copy over properties (In some projects just with plain old code, in other projects using an auto mapper)
I tend to create separate view models that contain just what I need to be displayed in the view. AutoMapper is a create tool for making this easier.

How do you elegantly program ASP.NET MVC when the View needs more than one Model?

A View accepts one Model.
But I need to draw HTML input controls for two models.
An example will illustrate:
I have a screen where I add Employees.
After adding their first name, last name and so on, I need the user to choose a number of Companies the Employees could be in.
The Companies are in one table.
The Employees are in another.
And a linking table joins them.
So it seems I need to pass the Companies to the View.
Can I pass multiple models to the view?
Or do I have to do an ugly database lookup in the View to find the Companies and manually spit out HTML for checkboxes without HTML helpers?
A Model doesn't have to consist of just one object or a single collection of one type of object. It can contain many objects and/or collections of objects. It seems that the model required for your page consists of at least collections of both employees and companies. If you have no type which fits this bill in your business object abstraction then you need to create a ViewModel for this page which can do the job.
This answer may help to explain how a ViewModel fits in MVVM ViewModel vs. MVC ViewModel
This is not entirely obvious - I'm sure it is to some guru types but for the rest of us trying to work things out its a bit more interesting.
Without going into detail I see a number of ways of solving this:
You need both sets of data so you need a view specific View Model
Your model is the Employee but you can still add other data to the ViewData - so make the Employee the model and pass the company data in as well as view data but not part of the model
(You may want to do this regardless of what model you use) Render the company selection elements as a separate view - which is where things get interesting - you obviously have to pass the existing selection, or a means to identify same, to the component view but do you have to pass the company list or could you, at this point, cheat a bit (prgamatically)? My feeling is that this is a partial view and that you need to pass it a company selection model (list of companies with selection indicated) but you could in theory do RenderAction and have an action that returns a view that goes to get the company selection for the specified employee - that way the overall view never sees the company data, that becomes a separate encapsulated problem - at least in terms of loading the data.
I think in this case where you're adding the employee either tweaking the model or adding the company list as supplementary data to the ViewData is sufficient, but for editing - assuming its required - rather than inserting you want a company selection list (all the companies with flags to indicate which are currently selected) rather than just a list of companies and at that point it all gets a bit more interesting

Resources