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

倖福魔咒の 提交于 2019-12-24 00:13:32

问题


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 ?


回答1:


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.




回答2:


What you described in point 2 is actually the solution I use the most and it makes sense to me: I use Automapper on the server side to map between Domain models and ViewModels (.Net objects) that are View specific and contain only the data the View needs. The Controller Action that is responsible for loading the View the first time, will databind the View to the ViewModel, so that the page is initialized quickly without the need to make an Ajax call. In the View itself I create the knockout viewmodel, assigning any initial values (if needed) by Json encoding the bounded ViewModel (for example using Asp.Net MVC i would do something like

var boundedViewModel = @Html.Raw(Json.Encode(Model));



回答3:


That is exactly how I would approach this problem. If this were a straight MVC app, you would still be creating viewmodels.

Sometimes for complicated data sets, I can see a use case for using something like Knockback, which takes the rich data model of backbone.js and combines it with knockout.js http://kmalakoff.github.com/knockback/



来源:https://stackoverflow.com/questions/10434203/defining-models-on-server-side-when-using-mvvm-with-knockout-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!