序列化包含数组的对象

时间:2013-02-18 15:54:32

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

- 这个问题已由我自己修复 -

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

2 个答案:

答案 0 :(得分:0)

GetData()函数中尝试此操作。

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

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

答案 1 :(得分: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;
    }
}

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