2

-这个问题已经自己解决了-

所以我正在尝试使用 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);
  });

4

2 回答 2

0

GetData()在你的函数中试试这个。

    return Newtonsoft.Json.JsonConvert.SerializeObject(result);

我从来没有遇到过 JSON.NET 的任何问题,而且我知道它支持匿名类型。

于 2013-02-19T00:42:45.680 回答
0
public class child
{
    public int id { get; set; }
    public String name { get; set; }

    public child(int id, string name)
    {
        this.id = id;
        this.name = name;
    }
}

我的错误是我没有设置公共属性

于 2013-02-19T11:16:09.907 回答