【问题标题】:How to convert json string to ko.observableArray([]), array of objects?如何将 json 字符串转换为对象数组 ko.observableArray([])?
【发布时间】:2016-03-23 14:35:31
【问题描述】:

我有一个 ViewModel 可用于淘汰框架和 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 调试器说:数据和类别不可用。

【问题讨论】:

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


    【解决方案1】:

    您根本不需要使用mapping

    在您的 ajax 调用 .done 中,您只需这样做:

    self.categories(data.categories);
    

    作为一个可观察的数组,categories 期望一个数组作为参数。而根据console.log(JSON.stringify(data))的结果为:{"categories":[{...}, {...}, ...],数组在接收到的datacategories属性上。

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

    【讨论】:

      猜你喜欢
      • 2021-05-12
      • 1970-01-01
      • 2013-08-29
      • 2016-10-09
      • 1970-01-01
      • 2012-05-08
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多