Mark Kadlec
Mark Kadlec

Reputation: 8460

Best way to pass data back to Server using Knockout.js and Viewmodel

We have an existing ViewModel that has a bunch of properties, but also has lists of enums in order to populate the dropdowns in the view.

I noticed that when you are using Knockout.js and trying to post the Json info back, when you call:

ko.toJSON(viewModel);

It converts all of the model when sending back, including the enums, which are not necessary when trying to send back to the Server to save the data.

I suggested just wrapping the data in a and doing a post, but is there a nice clean, simple way to post back only the data values without the enums using Knockout? What is the best way to do this? Should the ViewModel contain the enums or is that bad design?

Upvotes: 0

Views: 2250

Answers (2)

Cyanfish
Cyanfish

Reputation: 4163

One possibility is to structure your view model like this:

var viewModel = {
    enum1: ko.observableArray([...]),
    enum2: ko.observableArray([...]),
    data: {
        ... // other properties you want to post to the server
    }
};

And only post back the data property:

ko.toJSON(viewModel.data);

Another possibility, if you use Underscore.js, is to use the _.omit function:

ko.toJSON(_.omit(viewModel, "enum1", "enum2"));

Upvotes: 1

Joseph Gabriel
Joseph Gabriel

Reputation: 8520

Check out my answer to a similar question: https://stackoverflow.com/a/14629775/91189

Yes, your view model should contain all the data, enums, etc the view needs. The data you post to the server does not need to contain all the view model's data. A straightforward approach is, when you're ready to send data to the server, construct a model that contains just the data that the request needs.

A slightly different, more built-in approach is to expose the model as a property on your view model and bind your view to that where needed. That way the model is pre-constructed and ready to submit when you are.

Upvotes: 2

Related Questions