Tuesday, 23 July 2013

Insight ViewModel

Note: All this data has been copied from various sources for the purpose of knowledge sharing. Data content  can be either as it is or with little modification.
---------------------------------------------------------------------------------------------------------------------

So far you made your Views display hardcoded HTML, but in order to create dynamic web applications, the View template should receive information from the Controller. One common technique to be used for that purpose is the ViewModel pattern.

  • ViewModel allow you to shape multiple entities from one or more data models or sources in to a single object. It usually made to optimized for consumption and rendering by the views.



Why We Use ViewModel ?

1. If you need to pass more than one thing to a strongly-typed view (which is best practice),
    you will generally want to create a separate class to do so.

2. This allows you to validate your ViewModel differently than your domain model for
    attribute-based validation scenarios

3. Can be used to help shape and format data.
    e.g: need a date or money value formatted a particular way?
          ViewModel is the best place to do it.

4. The use of a ViewModel can make the interaction between model and view more simple

Best Practices When Using ViewModels

1. Put only data that you'll render (use in View) in the ViewModel

2. The View should direct the properties of the ViewModel, this way it fits better for rendering
    and maintenance

No comments:

Post a Comment