-this問題已被固定的目的是通過myself-序列化包含數組
SO我試圖使用knockoutJS並測試映射插件和我在與序列化,其包含一個對象的一些問題和array
下面是控制器我和下面的JavaScript,我遇到的問題是無論我嘗試(你可以看到註釋掉的嘗試修復)我不能讓兒童數組傳遞給JavaScript來顯示孩子 - {"id":5,"name":"Testing this works","children":"[{},{}]"}
是所有通過。
有人能指出我朝着正確的方向請
namespace TestingKnockout.Controllers
{
public class child
{
int id;
String name;
public child(int id, string name)
{
this.id = id;
this.name = name;
}
}
public class HomeController : Controller
{
public ActionResult Index()
{
return 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 this works",
children = childrenList
//children = Newtonsoft.Json.JsonConvert.SerializeObject(childrenList)
//children = new{ id = 2, name = "bob" }
};
//String resultsToHighlightJSON = Newtonsoft.Json.JsonConvert.SerializeObject(childrenList);
//return resultsToHighlightJSON;
return new JavaScriptSerializer().Serialize(result);// +resultsToHighlightJSON;
}
}
}
這是我的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) {
return 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 this out : " + Employee.children[1].name);
//ko.mapping.fromJS(updatedData,viewModel);
ko.mapping.fromJS(Employee,viewModel);
});
}
$(document).ready(function() {
ko.applyBindings(viewModel);
});
您是否已經使用小提琴手來看看什麼是真正被返回給客戶端JSON? – 2013-02-18 16:00:23
當我使用應用更新功能 – kaldhu 2013-02-18 16:27:35
啊,所有正在傳遞的是{「id」:5,「name」:「Testing this works」,「children」:「[{},{}]」}不是因爲你不能像這樣在C#中序列化一個泛型列表?嘗試將其更改爲數組,然後查看是否有效。 – 2013-02-18 18:45:00