Use jQuery Lazy Load with Knockout binding

by: Ruchita Kansara in: Programming tags: C#, ASP.NET MVC,

Recently I came across a requirement to use jQuery Lazy Load with Knockout binding. In this article, I will explain the steps for binding lazy loaded content to Knockout template.

Let’s Start

1. Create an ASP.NET Web Project > MVC 4 Framework.

2. Create  a new ContentController.cs file under Controller folder. Write new Action method.

public ActionResult LoadContent()
{
	return View();
}

3. Create a new View for above Action method. It will create LoadContent.cshtml file under Views > Content folder.

4. Install Knockout.js using NuGet and include it into your page along with jQuery.

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/knockout-3.1.0.js"></script>

5. Write the following HTML code with Knockout bindings to display your result.

<div id="page" style="width: 250px; height: 215px; overflow-y: scroll; background-color: aliceblue">
    <ul data-bind="foreach:numbersList">
        <li data-bind="text:number"></li>
    </ul>
    <span id="symbol">Loading...</span>
</div>

Here I have created a “div” tag which has vertical scrollbar and inside that div, I have an un-ordered list which binds each element of numbersList i.e. Knockout Observable Array to list item.

Now, <li data-bind=”text:number”></li> binds number (Knockout Observable) to list. 

6. After creating HTML code, write script to bind the data.

var arr = new Array();
    
function KnockoutViewModel(no)
{
	var self = this;
        self.number = ko.observable(no);
}

function ModelBinding()
{
        var self = this;
        self.numbersList = ko.observableArray([]);
}

var bind = new ModelBinding();
ko.applyBindings(bind);

for (var i = 1; i <= 10; i++)
{
        var obj = new KnockoutViewModel(i);
        arr.push(obj);      
}

bind.numbersList(arr);

This script will bind numbers 1-10 to the list.

7. Create an Action method to fetch next set of data on scroll down event.

public JsonResult LazyLoadContent(int page = 11)
{
	int[] numbers = new int[10];
           
	for (int i = 0; i < 10; i++)
	{                
		numbers[i] = page;
		page=page+1;
		TempData["LastPage"] = page;
	}
            
	return Json(numbers, JsonRequestBehavior.AllowGet);
}

This method returns next 10 numbers in JSON format. This method gets invoked whenever the scroll down event occurs. 

8. Add this additional code to your script which will help bind data on scroll event.

$("#page").scroll(function () {
	if ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) {           
		call();
		$('#symbol').empty();
	}
});

var page = 1;

function call()
{
        
	$.ajax({
		url: '@Url.Action("LazyLoadContent","Content")',
		data:{page:page+10},
         	success: function (data) {
               
		for (var i = 0; i < data.length; i++)
                {
                	var obj = new KnockoutViewModel(data[i]);
                    	arr.push(obj);
                }
                bind.numbersList(arr);
                page = page + 10;
		},
		error: function () { alert('error');}
	});
}

The above code snippet will check scroll bar position and if it is at the bottom of the “div” tag then it makes an AJAX call to the action in the Controller. It will fetch the next set of data as result, bind it and display the results on screen.

9. Output

Lazyloadwithknockout 01

Lazyloadwithknockout 02

Lazyloadwithknockout 03

Download Sample

Click here to download the sample application.