Ben
Ben

Reputation: 383

MVC4 Ajax load records on windows scroll

Using MVC4 and Ajax. I am loading 5 records and on windows scroll down load the next 5 records ..etc

Controller: (works)

    public JsonResult FetchData(int pageIndex = 0)
    {
      var model = ...
      ViewBag.count = pageIndex*2;

      return Json(model, JsonRequestBehavior.AllowGet);
    }          

View

javascript:

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

  function FetchDataFromServer() {
    var Id = $(".postcount").attr("Id");
    $.ajax({
        url: '@Url.Action("FetchData")',
        data: { pageIndex: Id },
        datatype: 'application/json',
        success: function () {
            //?
        },
        error: function () {
            alert("error");
        }
  });


 <div id="result">
   @Html.Partial("_ResultList",Model)
</div>

The first time the model gets passed to the partial view and data successfully loads. On scroll down the Action FeachData gets executed and I can see the data gets retrieved successfully.

My question when FeachData method passes the model, How do I pass the model to the Partial View and append to the existing records?

partial view excepts a model and has a @foreach (var item in Model){..} that loops and displays the data.

Thank you

Upvotes: 5

Views: 5485

Answers (2)

user3559349
user3559349

Reputation:

If you model is a collection, use .Take() and .Skip() to filter the records you want and return a partial view based on the results.

Controller

public ActionResult FetchData(int skipCount, int takeCount)
{
  var model = db.MyObjects.OrderBy(x => x.SomeProperty).Skip(skipCount).Take(takeCount);
  if (model.Any())
  {
    return PartialView("_ResultList", model);
  }
  else
  {
    return null;
  }
}

Script

var skipCount = 5; // start at 6th record (assumes first 5 included in initial view)
var takeCount = 5; // return new 5 records
var hasMoreRecords = true;

function FetchDataFromServer() {
  if (!hasMoreRecords) {
    return;
  }
  $.ajax({
    url: '@Url.Action("FetchData")',
    data: { skipCount : skipCount, takeCount: takeCount },
    datatype: 'html',
    success: function (data) {
      if (data === null) {
        hasMoreRecords = false; // signal no more records to display
      } else {
        $("#result").append(data);
        skipCount += takeCount; // update for next iteration
      }
    },
    error: function () {
      alert("error");
    }
  });
}

Edit: Alternative using JSON

Controller

public ActionResult FetchData(int skipCount, int takeCount)
{
  var model = db.MyObjects.OrderBy(x => x.SomeProperty).Skip(skipCount).Take(takeCount);
  return Json( new { items = model, count = model.Count() }, JsonRequestBehavior.AllowGet);
}

Script

var skipCount = 5; // start at 6th record (assumes first 5 included in initial view)
var takeCount = 5; // return new 5 records
var hasMoreRecords = true;

function FetchDataFromServer() {
  if (!hasMoreRecords) {
    return;
  }
  $.ajax({
    url: '@Url.Action("FetchData")',
    data: { skipCount : skipCount, takeCount: takeCount },
    datatype: 'json',
    success: function (data) {
      if (data.Count < 5) {
        hasMoreRecords = false; // signal no more records to display
      }
      $.each(data.items, function(index, item) {
        // assume each object contains ID and Name properties
        var container = $('<div></div>');
        var id = $('<div></div>').text($(this).ID);
        container.append(id);
        var name = $('<div></div>').text($(this).Name);
        container.append(name);
        $("#result").append(container);
      });
      skipCount += takeCount; // update for next iteration
    },
    error: function () {
      alert("error");
    }
  });
}

Upvotes: 6

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

Instead of Json return partial view from the action:

public ActionResult FetchData(int pageIndex = 0)
    {
      var model = ...
      ViewBag.count = pageIndex*2;

      return View("_ResultList",model);
    }  

and in Success callback you will have the response html, you need to append it to that div by using append():

success: function (response) {
            $("#result").append(response);
        }

You can also see this post. Infinite Scroll Paging in Asp.net mvc 4

Upvotes: 2

Related Questions