-这个问题已经自己解决了-
所以我正在尝试使用 knockoutJS 并正在测试映射插件,我在序列化包含和数组的对象时遇到了一些问题
下面是我拥有的控制器和下面的 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);
});