I get this JSON response from ASP.NET web method
{"d":[{"__type":"KnockoutWebFormsTest.Item","Id":1,"Name":"Item1","Description":"Item 1 Description"},{"__type":"KnockoutWebFormsTest.Item","Id":2,"Name":"Item2","Description":"Item 2 Description"}]}
Then using KnockoutJS I can bind data with this code,
Javascript:
function bindModel(data) {
var viewModel;
viewModel = ko.mapping.fromJSON(data);
ko.applyBindings(viewModel);
}
HTML:
<tbody data-bind="foreach: d">
<tr>
<td data-bind="text: Id"></td>
<td data-bind="text: Name"></td>
</tr>
</tbody>
This uses object type of d in foreach loop, But now what I need to use my server object type Item in foreach loop like,
<tbody data-bind="foreach: Item">
How can I achieve this?
Note : this is related to my previous question in SO
EDIT 1 :
Server Side Code (C#)
[WebMethod]
public static List<Item> GetItems()
{
List<Item> itemlist = new List<Item>
{
new Item {Id = 1, Name = "Item1", Description = "Item 1 Description"},
new Item {Id = 2, Name = "Item2", Description = "Item 2 Description"}
};
return itemlist;
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
EDIT 2 :
From this Javascript code
var jsonObject;
jsonObject = ko.mapping.fromJSON(data);
console.log(data);
console.log(jsonObject);
console.log(jsonObject.d);
I get
data
{"d":[{"__type":"KnockoutWebFormsTest.Item","Id":1,"Name":"Item1","Description":"Item 1 Description"},{"__type":"KnockoutWebFormsTest.Item","Id":2,"Name":"Item2","Description":"Item 2 Description"}]}
jsonObject
>Object {d: function, __ko_mapping__: Object}
>__ko_mapping__: Object
>d: Object[0]
>__proto__: Object
jsonObject.d
[]
You can't change the default behaviour from what I've seen.. since this is a WebMethod that returns JSON - from .NET 3.5 onwards, there was a breaking change to add a d property on payloads returned.
See here: http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/
Specifically:
So the wrapping of the "d" parameter prevents direct execution of the string as script. No Object or Array constructor worries..
What you can do, is assign this somewhere else, like so:
var jsonObject;
jsonObject = ko.mapping.fromJSON(data);
var viewModel = { Item: jsonObject.d };
ko.applyBindings(viewModel);
This will allow you to set the binding:
<tbody data-bind="foreach: Item">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With