从JSON响应创建可观察的挖空阵列

时间:2016-03-04 02:26:39

标签: javascript c# asp.net-mvc knockout-2.0

C#/ MVC /敲除/ JSON

我有以下javascript:

function Feed(data) {
    this.ID = ko.observable(data.ID);
    this.RSSName = ko.observable(data.RSSName);
    alert(data.RSSName + " " + data.ID);
}

function ViewModel() {
    self = this;
    self.CurrentFeeds = ko.observableArray([]);
    self.isLoading = ko.observable(false);
    self.StatusMessage = ko.observable("Loading");

    $.ajax({
        type: "GET",
        url: '@Url.Action("RSSList", "RSS")',
        success: function (data) {
            var feeds = $.map(data, function (item) {
                alert(item.RSSName + " " + item.ID + " 1");
                return new Feed(item)
            });
            self.CurrentFeeds(feeds);
            //self.CurrentFeeds(data);

        },
        error: function (err) {
            alert(err.status + " : " + err.statusText);
        }
    });

    self.save = function () {
        self.deleteFeed = function (feed) {
        };
    };
}

JSON响应(从fiddler复制)如下所示:

{"aaData":[{"ID":"0","RSSName":"Most Recent"},{"ID":"1","RSSName":"Website feed"}]}

控制器:

    public JsonResult RSSList()
    {
        var query = (from t in db.tblRSSFeeds
                     select new ViewModels.RSSList()
                     {
                         ID = t.pkID.ToString(),
                         RSSName = t.szFeedName
                     }).OrderBy( t => t.RSSName).ToList();

        var recent = new ViewModels.RSSList();
        recent.ID = "0";
        recent.RSSName = "Most Recent";
        query.Insert(0, recent);

        return Json(  query, JsonRequestBehavior.AllowGet);
    }

我认为我的问题与Feed(数据)功能有关,因为它只传回一条记录。我尝试设置self.CurrentFeeds(数据)也没有运气。 "警报"如上所示显示未定义,但我可以看到来自提琴手的数据......

由于某种原因,成功函数未正确查看数据以创建数组。这是为什么?

1 个答案:

答案 0 :(得分:2)

如果是回复:

{"aaData":[{"ID":"0","RSSName":"Most Recent"},{"ID":"1","RSSName":"Website feed"}]}

success回调更改为:

$.ajax({
   type: "GET",
   url: '@Url.Action("RSSList", "RSS")',
   success: function (data) {
           var feeds = $.map(data.aaData, function (item) {
           alert(item.RSSName + " " + item.ID + " 1");
           return new Feed(item)
       });
       self.CurrentFeeds(feeds);
   },
   error: function (err) {
       alert(err.status + " : " + err.statusText);
   }
});

我相信它有效,因为你试图映射一个对象而不是数组,所以你必须得到要映射的数组aaData