从 JSON 响应创建可观察的敲除数组

本文关键字:数组 观察 JSON 响应 创建 | 更新日期: 2023-09-27 18:37:14

C#/MVC/Knockout/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(data) 函数有关,因为它只传回一条记录。 我尝试设置自我。当前馈送(数据)也没有运气。 上面显示的"警报"显示未定义,但我可以看到来自小提琴手的数据......

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

从 JSON 响应创建可观察的敲除数组

如果是响应:

{"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