如何在mvc 4中将jquery延迟加载与ajax调用合并

时间:2014-04-25 13:16:18

标签: jquery asp.net-mvc-4 jquery-lazyload

我已经实现了一个功能,我使用MVC 4中的实体框架从数据库通过ajax调用获取记录。有超过2000条记录来自数据库并且需要更多时间来显示然后我决定改变方法现在我想要按照以下方式实现延迟加载方法:

CLICK HERE

我在控制器中创建了一个函数,我传递了pagenumber参数(并将pagesize设置为10)并在ajax调用中返回结果。

但我不明白如何使用延迟加载合并ajax调用。 实际上我在ajax调用中传递了页码参数。 所以我想按照以下给出:

1)向下滚动页面编号将增加1

2)使用增加的页码进行ajax调用

3)返回结果将以div显示 等等,直到最后的结果。

由于

1 个答案:

答案 0 :(得分:6)

延迟加载延迟加载长网页中的图片。在此图像中,只有用户滚动到视口外,才会加载视图。

要实施分页,您需要安装 PagedList.MVC NuGet包

将此添加到您的控制器

using PagedList;

请参阅this文档,了解实现分页,搜索和排序的完整方法。

要在滚动时实现动态加载数据,请参阅此示例

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    var pageIndex = 1;
    var pageCount;
    $(window).scroll(function () {
        if ($(window).scrollTop() == $(document).height() - $(window).height()) {
            GetRecords();
        }
    });
    function GetRecords() {
        pageIndex++;
        if (pageIndex == 2 || pageIndex <= pageCount) {
            $("#loader").show();
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetCustomers",
                data: '{pageIndex: ' + pageIndex + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                },
                error: function (response) {
                    alert(response.d);
                }
            });
        }
    }
    function OnSuccess(response) {
        var xmlDoc = $.parseXML(response.d);
        var xml = $(xmlDoc);
        pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
        var customers = xml.find("Customers");
        customers.each(function () {
            var customer = $(this);
            var table = $("#dvCustomers table").eq(0).clone(true);
            $(".name", table).html(customer.find("ContactName").text());
            $(".city", table).html(customer.find("City").text());
            $(".postal", table).html(customer.find("PostalCode").text());
            $(".country", table).html(customer.find("Country").text());
            $(".phone", table).html(customer.find("Phone").text());
            $(".fax", table).html(customer.find("Fax").text());
            $("#dvCustomers").append(table).append("<br />");
        });
        $("#loader").hide();
    }
</script>

完整文档和演示点击here