Systenics Solutions Logo
  • Home start here
  • Solutions services we provide
  • Products products we build
  • About Us who we are
  • Contact Us request a quote
  • Jobs work for us
  • Blog our views

Blog

Home / Blog

Use jQuery Lazy Load with Knockout binding

  • by:
  • in:
  • tags: ASP.NET MVC, C-Sharp
  • 0 Comments

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.

Share This Post:

About the Author

This post was written by on Monday March 31, 2014.

Related Posts
  • Create a Grid View with paging and sorting feature using ASP.NET MVC Razor and LINQ - 20 April 2013
comments powered by Disqus
< Older Newer >
All Categories
  • Programming
  • General
  • DevOps
Tags
  • .NET (9)
  • Ajax (1)
  • Android (3)
  • ASP.NET (1)
  • ASP.NET 4.5 (1)
  • ASP.NET 5 (1)
  • ASP.NET 6 (1)
  • asp.net core (1)
  • ASP.NET MVC (12)
  • AuctionWorx (2)
  • Bootstrap (4)
  • Build and Release (1)
  • CI (1)
  • ClickOnce (1)
  • ClientDependency (1)
  • Code Signing (1)
  • Continuous Integration (1)
  • C-Sharp (9)
  • devops (1)
  • ExpressJS (1)
  • Interview Process (1)
  • iOS (1)
  • Linux (1)
  • Lucene (1)
  • MVC (2)
  • NodeJS (1)
  • Phonegap (3)
  • Razor (4)
  • Salesforce (2)
  • Socket.IO (1)
  • SQL CE 3.5 SP2 (1)
  • SQL Server (1)
  • Sync (1)
  • Sync Framework v2.1 (1)
  • Umbraco 6 (6)
  • Umbraco 7 (4)
  • Visual Studio 2015 (1)
  • Visual Studio Online (1)
  • VMWare ESXI 6.0 (1)
  • WCF (1)
  • Windows (2)
  • WPF (2)

About Us

Systenics Solutions is a customized software development company. We specialize in building Cloud, Web, and Mobile based applications using the latest Cloud Technologies. Our fine-tuned agile processes help you smoothly progress from conceptualizing your ideas, building proto-types/wireframes to bringing your product to market, giving our clients complete visibility and control at all times. We strive to provide our global clients of various sizes with cost effective benefits of offshore development while providing expert technical services.


Microsoft Partner - Gold Cloud Platform

Contact Us

Systenics Solutions

The Affaires, Unit #F-1, 1st Floor, Plot #9, Sector - 17, Opp. Bhumiraj Costarica, Sanpada, Navi Mumbai - 400705, India

 

Telephone: +91-22-2781 0808

Email: info@systenics.com

Skype: saurabhn

Testimonials

"Coming from a non-technical background, Saurabh and his team at Systenics took my business idea and turned it into a fully functional application which surpassed my expectations! You can be sure with them that all your IT related concerns will be covered."

Shobhan, CEO - IITJobs Inc

"The ability Systenics showed in code signing and deploying my click once code in Microsoft visual was truly awesome. I interviewed and tested 6 different development companies and only one was actually able to get the job done - that was Systenics Solutions! Professional, courteous and reliable - I highly recommend them and am very happy and eager to continue growing our business relationship now and in the near future. Thank you Saurabh"

Andre Pierre

I contracted with Systenics about 6 months ago, in an effort to customize auction software for a new company I am launching in the US. The entire process was as smooth as could be. Their estimate for the project was reasonable, and very close to the final number. I would absolutely use this company again, and I have so much confidence in their ability to work with me, I even agreed to a support agreement with them long term. Their ability to communicate with me in the US was always very timely. They listened to my thoughts and ideas, and then suggested some changes, that made my software have even greater value. I cannot thank them enough, and would highly suggest their quality services to anyone. A completely satisfied customer!

Joe Lefebvre - Pharmabid, LLC

Systenics did a great job on our customization , they clearly understood the requirements and completed the task in a timely manner. They were very thorough in project discussions and made sure that we understood how the customization works and suggested improvements when required

Mike Singh - Dr. Liquidator

Copyright © 2012-2018 Systenics Solutions. All rights reserved.

BACK TO TOP