Question

I'm using a RESTful WebAPI service to return JSON with Hypermedia links and then tried to use KnockoutJS mapping to decode into the view model and it keeps failing although don't understand why. Am having to manually parse the stringified JSON which means my client has now become object specific removing the flexibility with the solution I was after.

The simplified example below returns the details of a single restaurant with a couple of actions to either book or email.

Here is the JSON

{
    "Id": 1,
    "Name": "Kings Head",
    "NickName": "Kings",
    "_links": {
        "book": {
            "href": "/resturant/1/book",
            "title": "Book"
        },
        "email": {
            "href": "/resturant/1/email",
            "title": "Email"
        },
        "self": {
            "href": "/resturant/1"
        }
    }
}

The code that works is:

var viewModel = {
   Name: ko.observable(),
   NickName: ko.observable()
};

$.getJSON('http://localhost:8080/resturants/1', function (jsonResult) {
   var str = JSON.stringify(jsonResult);
   var parsed = JSON.parse(str);
   viewModel.Name = (parsed.Name);
   viewModel.NickName = (parsed.NickName);
   ko.applyBindings(viewModel);
})

If I attempt to use:

viewModel = ko.mapping.fromJS(jsonResult);

it fails.

Any help appreciated.

Many thanks,

Shaun

Was it helpful?

Solution

If you are using the jsonResult straight from the service call, which I assume you are, then you need viewModel = ko.mapping.fromJSON(jsonResult); Check out the fiddle with each scenario setup.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top