How to Lazy load mvc4 webgrid rows using knockout.js ?

1.3k Views Asked by At

I have a web grid with large number of rows and I am not interested in paging the grid. I need to view only a particular number of rows initially. Then while scrolling I need to view rows one after the other. I have read it somewhere that it is possible with knockout.js. Do anyone have a sample code to share? Am working with MVC 4 Razor.

1

There are 1 best solutions below

3
On

I implemented similar control. It was tree view with button "Load more". A lot of items in observable array might slow down your app, especially when you are showing them, because it's a lot of DOM operations.

So, all my data pushes into ordinary array on page load. For data to be shown I have KO observable array. I am pushing more data into an observable array when I need to show it.

Here is basic example:

JavaScript:

$(function () {
    $.get("URL TO GET DATA FROM", function (data) {
        // data = [{name: "Andrei"}, {name: "James"}, {name: "Bill"}]
        var page = new PageModel(data);
        ko.applyBindings(page);
    });
});

function PageModel(data) {
    self = this;

    //Show items from this array on the page
    self.itemsToShow = ko.computed(function () {
        return self.allItems.slice(0, self.numberToShow);
    });
    self.numberToShow = 10;
    self.allItems = data;
    self.showMore = function () {
        self.numberToShow += 10;
    }
}

HTML Template:

<div data-bind="foreach: itemsToShow">
    <span data-bind="text: name"></span>
</div>

If you need to show more items, you can just call page.showMore();