difference between models and view models

2019-02-03 16:16发布

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?

4条回答
太酷不给撩
2楼-- · 2019-02-03 16:45

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.

查看更多
beautiful°
3楼-- · 2019-02-03 16:46

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.

  1. Domain Model: This represents a domain object in your application, like a SQL table if you are using an ORM (Linq2SQL, EF).

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

查看更多
4楼-- · 2019-02-03 16:57

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
查看更多
淡お忘
5楼-- · 2019-02-03 17:01

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!

查看更多
登录 后发表回答