noonand noonand - 24 days ago 13
JSON Question

Difficulty getting arrays to bind in KnockoutJS

I'm having difficulty getting my view to bind to view model data in Knockout. Some of it binds in the application but not the nested arrays.

In an attempt to reproduce the issue as an MVCE I created this jsFiddle; however the MVCE functions even worse than the actual code as the current address part of it doesn't work at all. I'm hoping that this is just unfamiliarity with something in jsFiddle though.

It's JSON that's returned from a WebAPI call in ASP.NET that looks as follows (non-MVCE text removed):

'{"CurrentAddress":{"ResidentFrom":2010,"Address":{"OfNoFixedAbode":false,"Line1":"A","Line2":"B","Line3":"C","Line4":"D","Line5":"E","PostCode":"3C"},"FullAddress":"A, B, C, D, E, 3C"},"HasPreviousAddresses":true,"PreviousAddresses":[{"ResidentFrom":2004,"ResidentTo":2010,"Address":{"OfNoFixedAbode":false,"Line1":"K","Line2":"L","Line3":"M","Line4":"N","Line5":"O","PostCode":"2B"},"FullAddress":"K, L, M, N, O, 2B"},{"ResidentFrom":1998,"ResidentTo":2004,"Address":{"OfNoFixedAbode":false,"Line1":"F","Line2":"G","Line3":"H","Line4":"I","Line5":"J","PostCode":"1A"},"FullAddress":"F, G, H, I, J, 1A"}]}';


Because the page can be used in either a new or edit scenario I then test as follows:

if ((serverModel !== null) || (serverModel !== undefined)) {
SetValues(viewModel, serverModel);
}


SetValues
attempts to put the variables into the viewModel, but it's all fairly straightforward stuff. It should really use some kind of mapping lib, but I'm figuring that I'll get a basic version of it working first.

The entire code can be seen at the previously mentioned jsFiddle

EDIT 2016-11-09
I put all of this in a standalone file and ran it through F12. The error I get back is as follows:

"Unable to process binding \"value: function (){return CurrentAddress().Address().ResidentFrom }\"\nMessage: Function expected"

gkb gkb
Answer

So, there is a lot of stuff going on here..

First, the CurrentAddress object is not being created as an observable after you parse your JSON. So change all the bindings like below -

<label data-bind="value: CurrentAddress.Address().ResidentFrom"></label>

Also, I observed that you have not defined any property named FullAddress but you have used it in your bindings; so it was throwing error too.

Please refer to this fiddle (Oops! I updated your original one..)

Comments