如何获取ajax请求的有限记录

时间:2017-06-30 09:22:34

标签: jquery ajax asp.net-mvc entity-framework pagination

我的数据库中有10,000条记录。我用AJAX来获取记录。我在JSON中获得10,000条记录,但我希望它能够获取前100条记录,然后在下一个请求中再获取100条,依此类推。

我已应用切片方法,但它不适用于条件类型。我想应用分页,但我不知道如何应用分页。

$().ready(function(){
  $.ajax({
    url: "http://localhost:66252/Home/Getoptions", 
    success: function(result) { 
      //result has 10000 records 
    }
  });
});

1 个答案:

答案 0 :(得分:1)

这就是我的做法,

第一次加载:

var pageSize = 100; // See, this is my default page size. You can change it.
$.ajax({
url: "http://localhost:66252/Home/Getoptions", 
data:{ skip: 0, take:100 },
success: function(result) { 
  var total = result.length;
  if (total > pageSize) {  // pageSize is 100, we declared on top
     var pageTotal = Math.ceil(total / pageSize);
     var j;
     for (var i = 0; i < pageTotal; i++) 
     {
       j = i + 1;
       //Here I'm creating li for all the pages. You can create any number of li then create a button called Next. Pass the value in Next button.
       var pages = '<li class="_li"><a id="page_' + j + '" class="pageNumber" style="margin-left:0px;" href="javascript:;">' + (i + 1) + '</a></li>';
       $('#_ul').append(pages); //This is my id of Ul from HTML
     }
   }
 });

在页码上点击:

$(document).on("click", ".pageNumber", function () {        
    var value = $(this).attr('id').split('_')[1];
    var skip = value == 1 ? 0 : (value * pageSize) - pageSize;
    //Then call once again your ajax method here by passing skip value
    $.ajax({
      url: "http://localhost:66252/Home/Getoptions", 
      data:{ skip: skip, take:100 },
      success: function(result) { 
      var total = result.length;
      if (total > pageSize) {
        var pageTotal = Math.ceil(total / pageSize);
        var j;
        for (var i = 0; i < pageTotal; i++) 
        {
          j = i + 1;
          //Here I'm creating li for all the pages. You can create any number of li then create a button called Next. Pass the value in Next button.
          var pages = '<li class="_li"><a id="page_' + j + '" 
                       class="pageNumber" style="margin-left:0px;" 
                       href="javascript:;">' + (i + 1) + '</a></li>';
          $('#_ul').append(pages); //This is my id of Ul from HTML
        }
      }
    });
   });

然后在Action Method中,您可以检索查询字符串的值,例如

string _skip = Request.QueryString["skip"];
string _take = Request.QueryString["take"];

然后,您可以在LinqEntity Framework查询中添加跳过采取方法,例如,

var result = 
   myContext.GetData.Skip(int.Parse(_skip)).Take(int.Parse(_take)).ToList();
return json(result,jsonRequestBehaviour.AllowGet);

注意:请根据您的要求相应更改CSS或HTML。例如,您的UI的BG颜色,或点击的Li颜色,或启用禁用li等等。

希望有所帮助:)