Wednesday, 15 February 2012

c# - Serializing an object containing an array -



c# - Serializing an object containing an array -

-this problem has been fixed myself-

so i'm trying utilize knockoutjs , testing mapping plugin , i'm having problems serializing object contains , array

below controller have , javascript below that, issue have no matter seek (you can see commented out attempts fix) can not array of children pass javascript display children -{"id":5,"name":"testing works","children":"[{},{}]"} passed.

someone able point me right direction please

namespace testingknockout.controllers { public class kid { int id; string name; public child(int id, string name) { this.id = id; this.name = name; } } public class homecontroller : controller { public actionresult index() { homecoming view(); } public virtual string getdata() { list<child> childrenlist = new list<child>(){ new child(2, "bob"), new child(4, "dave") }; var result = new { id=5, name="testing works", children = childrenlist //children = newtonsoft.json.jsonconvert.serializeobject(childrenlist) //children = new{ id = 2, name = "bob" } }; //string resultstohighlightjson = newtonsoft.json.jsonconvert.serializeobject(childrenlist); //return resultstohighlightjson; homecoming new javascriptserializer().serialize(result);// +resultstohighlightjson; } } }

and javascript:

<script language="javascript" type="text/javascript"> var originaldata = { id: 1, name: "main", children: [] }; var updateddata = { id: 1, name: "main", children: [{ id: 2, name: "bob" }, { id: 3, name: "ted"}] }; function child(id, name) { this.id = ko.observable(id); this.name = ko.observable(name); } var options = { children: { key: function (data) { homecoming ko.utils.unwrapobservable(data.id); } } } var viewmodel = ko.mapping.fromjs(originaldata, options); viewmodel.counter = 1; viewmodel.addchild = function () { viewmodel.children.push(new child(++viewmodel.counter, "new")); }; viewmodel.applyupdate = function () { var basepath="<%: url.content("~/") %>"; var url = basepath + 'home/getdata/'; $.get(url, function (response) { var employee = $.parsejson(response); $("#editlink").html("testing out : " + employee.children[1].name); //ko.mapping.fromjs( updateddata,viewmodel); ko.mapping.fromjs( employee,viewmodel); }); } $(document).ready(function() { ko.applybindings(viewmodel); });

try in getdata() function.

homecoming newtonsoft.json.jsonconvert.serializeobject(result);

i've never had problems json.net , know fact supports anonymous types.

c# javascript asp.net-mvc-3 knockout.js knockout-mapping-plugin

No comments:

Post a Comment