Search code examples
asp.net-mvc-3mvvmknockout.jssinglepage

Defining models on server side when using MVVM with Knockout.js


I am planning to use knockout.js and MVVM pattern on the client side for a Single Page application. So Models, ViewModels would be defined on the client side. I am confused about how we have to structure on the server side.

  1. Now, would controllers just return domain model itself ? Would all the mapping from domain model to ViewModel happen only on the client side ?

  2. In my solution, there is wide gap between the Domain model and the ViewModel. So the above approach would result in a lot of data being returned to client side unnecessarily. Though it seems like overkill, I am thinking about repeating ViewModel and InputViewModel definitions (former represents data rendered, latter represents data to be posted back to controller actions) on server side and also having a mapping layer (based on automapper) to map Domain models to ViewModels on the server side. Does this make sense ? Or is there a better approach ?


Solution

  • I would suggest that you work out what data your view models actually need, then have the controllers build up a server-side view model that contains that data and send it to the client in a JSON format.

    This way you are not sending unnecessary data over to the client (or back), you are still able to do much of the heavy lifting on the server and the knockout view models can do what they are meant for: presenting the data to be used by the view.