Kristian Nissen
Kristian Nissen

Reputation: 1184

Asp.net MVC 5 Modelbinding multiple JSON objects (knockoutjs)

Ok. I've encountered a problem that i just can't understand.

First of all, i'm trying to post several ko.observableArrays to the controller as JSON and modelbinding them seperately. When i post only one and don't name it in the data attribute of .ajax it posts just fine and modelbinds flawlessly.

This is my a snippet from my viewModel and is how i am attempting to post the two JSON objects.

        self.timeRanges = ko.observableArray();
        self.geoRequirements = ko.observableArray();

        self.saveWorkWish = function() {


                $.ajax({
                    url: "@Url.Action("SaveWorkWish")",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                data: {
                    timeRanges: ko.toJSON(self.timeRanges()),
                    geoRequirements: ko.toJSON(self.geoRequirements())
                },

                complete: function (data) {
                    console.log(data);
                }
            });

        };

My Action

   public JsonResult SaveWorkWish(IList<JSONTimeRanges> timeRanges, IList<JSONGeoRequirements> geoRequirements)
    {

        // do stuff

    }

I get this exception: Invalid JSON primitive: timeRanges.

Interesting to note is that, when i do:

                $.ajax({
                    url: "@Url.Action("SaveWorkWish")",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                data: ko.toJSON(self.timeRanges()),

                complete: function (data) {
                    console.log(data);
                }
            });

And

   public JsonResult SaveWorkWish(IList<JSONTimeRanges> timeRanges)
    {

        // do stuff

    }

It works just fine.

Lastly a thing that i noticed, and is likely the cause of the error is that:

When i post 2 Jsons like in the example, this is what chrome tells me i post: timeRanges=%5B%7B%22startDate%22%3A%2214-09-2014%22%2C%22endDate%22%3A%2220-09-2014%22%2C.....etc..

and in the working example:

it is a well formated and readable JSON object.

So it seems like the error is indeed correct and that i am not sending valid JSON to the controller.

But..what am i doing wrong?

Upvotes: 1

Views: 422

Answers (1)

Marian Ban
Marian Ban

Reputation: 8188

Try to convert observables to JSON first and then convert the whole object to json string:

data: JSON.stringify({
    timeRanges: ko.toJS(self.timeRanges()),
    geoRequirements: ko.toJS(self.geoRequirements())
}),

Upvotes: 1

Related Questions