loading a knockout.js observableArray() from .ajax() call

后端 未结 5 1178
半阙折子戏
半阙折子戏 2021-02-01 20:10

This puzzles me. It must be something small I\'m not seeing. I\'m trying to load a very simple observableArray in knockout with an ajax call.

javasc

5条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 20:21

    Here is what I done in my MVC .net app with knockout and jquery.

    // Scripts/groItems.js
    (function () {
    
        var ViewModel = function () {
            items = ko.observableArray(),
                ItemName = ko.observable(),
                Img = ko.observable(),
                Qty = ko.observable()
        }
    
        $.getJSON('/Items2/AllItems', function (data) {
            for (var i = 0; i < data.length; i++) {
                self.items.push(data[i]);
            }
        });
    
        var vm = new ViewModel();
    
        $(function () {
            ko.applyBindings(vm);
        });
    
    }());
    @model IEnumerable
    @{
        ViewBag.Title = "Index";
    }
    
    

    @Html.ActionLink("Create New", "Create")

    Item name img qty
    @section Scripts { }

    Following is part of my code at the Items2Controller.cs

        private GroContext db = new GroContext();
        public JsonResult AllItems()
        {
            return Json(db.Items.ToList(), JsonRequestBehavior.AllowGet);
        }
    

    Hope this will help. Thanks

提交回复
热议问题