user2113657
user2113657

Reputation: 191

Knockoutjs observable array to List<string>

I have searched high and low, and tried many different options, but can't figure out what is going wrong here.

I have a knockoutjs viewmodel, which looks like this:

{"Id":0,"Type":"post","Title":"adsf","AuthorId":0,"Description":"adsfadsf","ChosenCategoryValues":["7","8","9"]}

(some fields omitted for brevity)

Everything gets passed back to the controller just fine, except ChosenCategoryValues. That's an observableArray on the client side, a List<string> on the server side. It always comes back null, unles string with all the values in the first item which I would then have to string parse.

$.post("/serverurl", viewmodel, function (response) { do some stuff }, "json"); is how it's being sent to the server.

I've tried ko.toJS to make it a simple array, with no result.

I'm sure it's something basic, I'm new to knockoutjs, but I've been at this for far too long now, and none of the suggestions I've found online have been able to help.

Upvotes: 3

Views: 1026

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

In order to send view model data you should get view model data into JSON (remember - observables are simple functions), which is achieved via call to ko.toJSON() function.

Also you need to tell server, that you are sending JSON data. You can't achieve it with jQuery post() method - dataType parameter affects only expected server response type, but it does not affect request content type. So, simply use jQuery ajax() method:

$.ajax({
    url: '/serverurl',
    type: 'POST',
    data: ko.toJSON(viewmodel),
    contentType: 'application/json',
    success: function(response) {
        // do some stuff
    }
});

Upvotes: 2

Arjan Einbu
Arjan Einbu

Reputation: 13692

As I commented above, you should use fiddler to look at the request. I suspect that your data isn't being sent as json. When your values are sent as ordinary html post values, the collection typically isn't mapped.

I'd suggest creating the actual json to be sent to the server with JSON.stringify as shown here:

$.post("/serverurl", JSON.stringify(viewmodel), function (response) { do some stuff }, "json");

Upvotes: 1

Related Questions