In MVC, what is a ViewModel?

前端 未结 2 357
Happy的楠姐
Happy的楠姐 2020-12-06 04:27

Am I right in thinking it\'s almost like a wrapper for all the objects necessary for a View?

For example, say you had an online store that sold music and dvds. On yo

2条回答
  •  心在旅途
    2020-12-06 05:17

    Your understanding is mostly correct, but it's not complete.

    The ViewModel may also perform conversions from the type of data that your Model carries to the type of data your View can conveniently work with; this might even mean that the ViewModel does not carry Models directly but other vessels that carry (possibly a subset of) the same information in a more suitable format.

    Consider that you could have a Library model that aggregates Albums and DVDs -- the difference between such a model and the corresponding ViewModel is precisely that the Model doesn't care (or even know about) the View while the ViewModel has the express purpose of facilitating it.

提交回复
热议问题