如何将json字符串转换为ko.observableArray([]),对象数组?

时间:2015-12-17 07:50:41

标签: json ajax asp.net-mvc knockout.js

我有一个ViewModel与knockout框架和ajax一起使用。我可以使用ajax.Save将新项目保存到数据库,但是当我想要检索保存的数据时我遇到了问题。这是代码。

ViewModel中的代码:

self.Categories = ko.observableArray([]);
self.Message = ko.observable("");
elf.GetCategories = function () {
    $.ajax({
        url: "/Admin/Categories",
        cache: false,
        type: "GET",
        datatype: "json",
        contenttype: "application/json;utf8"
    }).done(function (data) {
        self.Categories(ko.mapping.fromJS(data));
    }).error(function (err) {
        self.Message("Error! " + err.status);
    });
}

console.log(JSON.stringify(data));返回:

{"categories":[{"Id":1,"Name":"Learning","UrlSlug":"0-learning","Description":"learning"},
{"Id":2,"Name":"Topics","UrlSlug":"0-topics","Description":"posts"},
{"Id":3,"Name":"Shares","UrlSlug":"category-shares","Description":"shares"},
{"Id":4,"Name":"Projects","UrlSlug":"category-projects","Description":"project"}]}

控制器中的代码是:

[HttpGet]
public ContentResult Categories()
{
    var categories = _weblogServices.Categories();
    return Content(JsonConvert.SerializeObject(new {categories}), "application/json;utf8");
}

问题是self.Categories = ko.observableArray([]);总是空的,没有任何数据。我也尝试了这些项目,但没有改变:

ko.mapping.fromJS(data, self.Categories);
self.Categories(ko.mapping.fromJS(data));
self.Categories(ko.mapping.fromJSON(data));
ko.mapping.fromJS(data, {}, self.Categories);

我有一个简单的表格:

<table id="tblCategory" class="table table-striped table-bordered 
  table-responsive table-condensed table-hover">
<thead>
  <tr>
    <th class="text-center">Name</th>
    <th class="text-center">Url Slug</th>
    <th class="text-center">Description</th>
  </tr>
</thead>
<tbody data-bind="foreach: Categories">
  <tr>
    <td><span data-bind="text: Name"></span></td>
    <td><span data-bind="text: UrlSlug"></span></td>
    <td><span data-bind="text: Description"></span></td>
    <td><button type="button" class="btn glyphicon glyphicon-pencil"
         title="Edit" data-bind="click:$data.GetSelected"></button></td>
    <td><button type="button" class="btn glyphicon glyphicon-trash"
         title="Delete" data-bind="click:$data.DeleteSelectedCategory">/button></td>
  </tr>
</tbody>
</table>

所以,问题是如何将JSON数据转换为observableArray([])?

更新: Chrome调试器说:数据和类别不可用。

1 个答案:

答案 0 :(得分:3)

您根本不需要使用mapping

在你的ajax电话.done中,你只需要这样做:

self.categories(data.categories);

作为一个可观察数组,categories期望数组作为参数。根据{{​​1}}的结果:console.log(JSON.stringify(data)),数组位于收到的{"categories":[{...}, {...}, ...]的{​​{1}}属性中。

您不需要使用映射,因为您只需要在数组中显示对象,并且您不想编辑其属性。因此,它们可以保留为常规JavaScript对象,而不具有可观察的属性。