Reputation: 1393
I am building an ASP.NET MVC application which takes advantage of ViewModels using AutoMapper. However, I was thinking of using KnockoutJS for 'AJAX heavy' pages but that means I would also have to create ViewModels for KnockoutJS.
The major downside I can think of having two separate ViewModels is maintainability. Is there a better solution than creating two ViewModels? Also, reading a few other posts this means that the client-side ViewModel will have to be aware of the server-side which is bad practice and tightly couples the two together.
I must admit I haven't really used KnockoutJS in the past, but have read/gone through a few tutorials so I am a bit agnostic on this matter. Any help would be appreciated.
Upvotes: 2
Views: 1294
Reputation: 6830
The duplicity can be to a great extent reduced by the following approach:
@model ViewModel
<script src="@Url.Content("~/Scripts/knockout.mapping-latest.js")" type="text/javascript"></script>
...
<script type="text/javascript">
function ViewModel(initData) {
var self = this;
ko.mapping.fromJS(initData, {}, self);
// Add custom view model logic
...
// Logic for persisting the current state of the model back to the server
self.Save = function() {
$.ajax('/model-uri', {
type: 'POST',
contentType: "application/json",
data: ko.toJSON(self)
});
};
var initialData = @(Html.Raw(JsonConvert.SerializeObject(Model)));
var model = new ViewModel(initialData);
ko.applyBindings(model);
</script>
Note that we're serializing the server-provided view model to a JavaScript object and then making its properties observable using the ko.mapping
plugin which saves us duplicating the view model definition on the client side. We also employ the ko.toJSON
utility function when sending the updated model back to the server.
Upvotes: 3