Load Data while Scrolling Page Down with jQuery in ASP.NET MVC

In my previous post I explained about how to load data while scroll down where we are loading images while scrolling down. in this Post will explain you how to load data from server while scroll down using ASP.NET MVC4
Approach:
We have to display student records from Database.
Initially display 5 students record on page and as user scroll down fetch next student record from server and append it to last Student on page. To append student at the bottom of page we are using Jquery template.
Remaining things are same.
First include two main scripts

 <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
 <script src="@Url.Content("~/Scripts/jquery.tmpl.js")" type="text/javascript"></script>

The 2nd script is for jQuery template. download jquery-tmpl

Now when user scrolls down and scrollbar is at bottom of page catch the event using script as below

$(window).scroll(function() {
    if ($(window).scrollTop() == $(document).height() -$(window).height()) {
       AddStudentRecord();
    }
});

In this event call the AddStudentRecord() function get next student record.
Here is AddStudentRecord function


function AddStudentRecord() {
        $.ajax({
            type: 'Get',
            url: 'Student/getStudent',
            data: { lastStudent: parseInt($("#hdnStudentCount").val()) + 1 },
            async: false,
            dataType: "html",
            success: function (data) {
                data = JSON.parse(data);
                for (var i = 0; i < data.length; i++) {
                    if (data[i] != '') {
                        $("#studentTemplate").tmpl(data[i]).appendTo("#divMain");
                        var ID = (data[i]["ID"]);
                        $("#hdnStudentCount").val(parseInt(ID));
                    }
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
    }

We are using a hidden field to store the last studentID, initilizing it on page load and updating it when new record is appended at the bottom.

 $().ready(function () {
        $("#hdnStudentCount").val(5);
    });

<input type="hidden" id="hdnStudentCount" />

In this approach we are loading student record as user scroll down.
We are displaying student record using jquery template.
Observe the function AddStudentRecord where we are passing student record to student template and append it to bottom of page.
Here is template

<script id="studentTemplate" type="text/x-jquery-tmpl">
    <div class="divOuter" >
        <div> ID :  ${ID}</div>
        <div> Name : ${Name} </div>
        <div> Address :${Address} </div>
        <div> SchoolName : ${SchoolName} </div>
        <div> City :  ${City} <div>
        <div> State : ${State} </div>
    </div>
</script>

on view page we are adding first 5 record on page using model

<div id="divMain" >
@using (Html.BeginForm())
{
    foreach (var item in Model.students)
    {
    <div class="divOuter" >
        <div> ID :  @item.ID</div>
        <div> Name : @item.Name </div>
        <div> Address : @item.Address </div>
        <div> SchoolName : @item.SchoolName </div>
        <div> City :  @item.City </div>
        <div> State : @item.State </div>
    </div>
    }
}
</div>

Now on controller side we have two methods one will be index and 2nd will return next student record


public ActionResult Index()
{
    StudentViewModel obj = new StudentViewModel();
    List<Student> students = Student.getStudent();
    IEnumerable<Student> students1 = students.Where(x => x.ID < 6);
    obj.students = (List<Student>)students1.Cast<Student>().ToList();
    return View(obj);
}

public JsonResult getStudent(int lastStudent)
{
    List<Student> student = Student.getStudent().Where(x => x.ID == lastStudent).Cast<Student>().ToList();
    return Json(student, JsonRequestBehavior.AllowGet);
}

Here we are using student model and Student View Model(StudentViewModel). collecting data from student model and passing it to view model.

Complete Code

View Page


@model LoadData.Models.StudentViewModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2> Student </h2>
<style type="text/css" >
.divOuter{ border: solid 1px red; padding:20px; }
.divOuter div{ padding:3px;}
</style>
 
<script type="text/javascript" language="javascript">
    $().ready(function () {
        $("#hdnStudentCount").val(5);
    });

    function AddStudentRecord() {
        $.ajax({
            type: 'Get',
            url: 'Student/getStudent',
            data: { lastStudent: parseInt($("#hdnStudentCount").val()) + 1 },
            async: false,
            dataType: "html",
            success: function (data) {
                data = JSON.parse(data);
                for (var i = 0; i < data.length; i++) {
                    if (data[i] != '') {
                        $("#studentTemplate").tmpl(data[i]).appendTo("#divMain");
                        var ID = (data[i]["ID"]);
                        $("#hdnStudentCount").val(parseInt(ID));
                    }
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
    }

    $(window).scroll(function () {
        if ($(window).scrollTop() == $(document).height() - $(window).height()) {
            AddStudentRecord();
        }
    });
</script>

<script id="studentTemplate" type="text/x-jquery-tmpl">
    <div class="divOuter" >
        <div> ID :  ${ID}</div>
        <div> Name : ${Name} </div>
        <div> Address :${Address} </div>
        <div> SchoolName : ${SchoolName} </div>
        <div> City :  ${City} <div>
        <div> State : ${State} </div>
    </div>
</script>
  
<input type="hidden" id="hdnStudentCount" />

<div id="divMain" >
@using (Html.BeginForm())
{
    foreach (var item in Model.students)
    {
    <div class="divOuter" >
        <div> ID :  @item.ID</div>
        <div> Name : @item.Name </div>
        <div> Address : @item.Address </div>
        <div> SchoolName : @item.SchoolName </div>
        <div> City :  @item.City </div>
        <div> State : @item.State </div>
    </div>
    }
}
</div>

Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LoadData.Models;

namespace LoadData.Controllers
{
    public class StudentController : Controller
    {
        public ActionResult Index()
        {
            StudentViewModel obj = new StudentViewModel();
            List<Student> students = Student.getStudent();
            IEnumerable<Student> students1 = students.Where(x => x.ID < 6);
            obj.students = (List<Student>)students1.Cast<Student>().ToList();
            return View(obj);
        }

        public JsonResult getStudent(int lastStudent)
        {
            List<Student> student = Student.getStudent().Where(x => x.ID == lastStudent).Cast<Student>().ToList();
            return Json(student, JsonRequestBehavior.AllowGet);
        }
    }
}

Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LoadData.Models
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string SchoolName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public bool Status { get; set; }

        public static List<Student> getStudent()
        {
            List<Student> student = new List<Student>()
            {
                new Student() { ID =1, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = true }, 
                new Student() { ID =2, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = false }, 
                new Student() { ID =3, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = true }, 
                new Student() { ID =4, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = false }, 
                new Student() { ID =5, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = true }, 
                new Student() { ID =6, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = false }, 
                new Student() { ID =7, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = true }, 
                new Student() { ID =8, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = false }, 
                new Student() { ID =9, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = true }, 
                new Student() { ID =10, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = false }, 
                new Student() { ID =11, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = true }, 
                new Student() { ID =12, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = true }, 
                new Student() { ID =13, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = false }, 
                new Student() { ID =14, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = true }, 
                new Student() { ID =15, Name="Abc", SchoolName="Engg",  Address="Pune", City="Pune" , State="Maharashtra", Status = false } 
            };
            return student;
        }
    }
}

view Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LoadData.Models
{
    public class StudentViewModel
    {
        public List<Student> students = new List<Student>();
    }
}

Download the complete code

Load Data while Scrolling Page Down with jQuery in ASP.NET MVC

Load Data while Scrolling Page Down with jQuery in ASP.NET MVC

Related Link
Load Data while Scrolling Page Down with jQuery in ASP.NET

Advertisements
This entry was posted in jQuery, MVC and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s