首页 > 代码库 > MVC中实现加载更多

MVC中实现加载更多

需要实现的功能:

  1. 数据太多想初次加载部分数据,在底部加上“加载更多”按钮
  2. 点击后加载第二页数据(从数据库只取指定页数据)后接在已有数据后面(类似于android中的下拉加载更多)
  3. 每次加载时显示“正在加载……”

网上找了一些方法,类似于MvcPager分页组件,用的是v1.5.0版,但后台需要将分页后的对象列表ToPagedList,需要在MvcPager源码中加入public static PagedList<T> ToPagedList<T>(this IList<T> list, int pageIndex, int pageSize, int? totalCount)方法,控件详见  MVC中局部视图的使用 一文。

 

主页面Index的View中添加局部视图:

    <div id="goodslist" class="goodslist">       @{Html.RenderPartial("_ProductListIndex", Model);}    </div>

 

其中的Model是在Index返回Model

public ActionResult Index(int pageIndex = 1, int pageSize = 4, string viewName = "_ProductListIndex")        {            int recordCount = 0;//总记录数            ProductDomain _productDomain = new ProductDomain();            List<Product_Entity> _productlist = _productDomain.GetProduct( pageIndex, out recordCount, 0, pageSize);            PagedList<Product_Entity> _productPageList = _productlist.ToPagedList(pageIndex, pageSize, recordCount);            if (base.Request.IsAjaxRequest())            {                return this.PartialView(viewName, _productPageList);            }            return View(_productPageList);        }     

其中Request.IsAjaxRequest()中判断是否通过分页页码进来的,ToPagedList需要用到改造后的MvcPager组件(见上文)

 

局部视图_ProductListIndex

@using Webdiyer.WebControls.Mvc@model PagedList<Domain.Shop.Product_Entity><div id="ProductListDiv">    @if (Model != null && Model.Count > 0)    {                foreach (var item in Model)        {        <div class="goodslist_row">                <div class="goodslist_col01 item">                         <div class="item_title">@item.product.title</div>                    <div class="item_price" style="font-size: 12px;">@String.Format("{0:0.00}{1}", item.product.Price,"元")                    </div>                </div>        </div>        }        <div>            <div style="clear: both;">            </div>            <div id="nonedata" class="nonedata" style="display: none;">                正在获取数据,请稍候...            </div>            <div style="clear: both;">            </div>            <div class="foot">                @Html.AjaxPager(Model, new PagerOptions                   {                       Id = "divPage",                       ShowNumericPagerItems = false,                       ShowPrev = false,                       ShowFirstLast = false,                       NextPageText = "查看更多商品>>",                       ShowDisabledPagerItems = false,                       AlwaysShowFirstLastPageNumber = false,                       PageIndexParameterName = "pageIndex",                       NumericPagerItemCount = 3,                       CssClass = "moregoods",                       SeparatorHtml = ""                   }, new AjaxOptions { UpdateTargetId = "ProductListDiv", LoadingElementId = "nonedata", LoadingElementDuration = 1000, InsertionMode = InsertionMode.InsertAfter })            </div>        </div>    }</div>

注意几点:

@Html.AjaxPager需要放在局部视图中,否则页码无法更新,由于是要加载到原数据后面因此设置 InsertionMode = InsertionMode.InsertAfter

其中注意的是ShowPrev = false 否则翻页后会显示“上一页” ,@Html.AjaxPager其它属性可 下载MvcPager源码PagerTest.rar 查看

但最重要的是还需要更改jquery.unobtrusive-ajax.js源码,否则会出现多个 “查看更多”

 

  需要更改后的jquery.unobtrusive-ajax.js下载

  

   点击查看更多时效果

现在问题来了,似乎达到效果了,但最重要的问题是初次加载 不显示“正在获取数据,请稍候...”,因为首次是直接由Model生成,没有从页码进去,无法执行beforeSend函数。

观察jquery.unobtrusive-ajax源码,其原理是异步从后台取数据然后经过模板解析后拼接到指定元素后面。

下面弃用MvcPager组件,自己改装,利用Get异步获得数据

js:

          var _pageIndex = 1;            $("#goods").click(function () {             LoadData(_pageIndex);            });            //按传参加载数据列表            function LoadData(pageIndex){                $("#nonedata").show(1000);                 //默认加载                var href = "http://www.mamicode.com/ProductListIndex";                if(pageIndex !=null && pageIndex !=""){                  href+="&pageIndex="+pageIndex;                }                $.ajax({                        url:href,                        type:"GET",                        success: function (data, status, xhr) {                          if(data.indexOf(‘nonedata‘) !=-1){                              $("#goods").hide(1000);                              if(_pageIndex==1){                                $("#goodslist").append(data);                              }                           }else{                               $("#goodslist").append(data);                               _pageIndex ++;                           }                        },                        complete: function () {                           $("#nonedata").hide(1000);                        }                });                            }                                //加载默认数据               LoadData(1);

 

$.ajax获得数据后拼接,前后显示隐藏加载提示,并初次加载由前台执行,这样就可实现自己控制 加载提示了。

Control中要进行页码判断,结合前台数据,否则会出现页码不断递增的情况。

 public ActionResult ProductListIndex(int pageIndex = 1, int pageSize = 4, string viewName = "_ProductListIndex")        {            int recordCount = 0;//总记录数            ProductDomain _productDomain = new ProductDomain();            List<Product_Entity> _productlist = _productDomain.GetProduct( pageIndex, out recordCount, 0, pageSize);            int totalPageCount = (int)Math.Ceiling(recordCount / (double)pageSize);            if (pageIndex >totalPageCount )            {                //超过数据总数则返回空                _productlist = new List<Product_Entity>();            }            return this.PartialView(viewName, _productlist);        }

 

在Index页只需要指定加载的框架:

    <div id="goodslist" class="goodslist">    </div>    <div style="clear: both;">    </div>    <div id="nonedata" class="nonedata">    正在获取数据,请稍后……    </div>    <div style="clear: both;">    </div>    <div class="foot">        <a href="javascript:void(0)" class="moregoods" id="goods">查看更多商品>></a>    </div>

 

最后初次加载实现效果

总的来说是利用异步获得数据利用局部视图装载数据(不用自己拼字符串)然后加载到指定框架中。

 

MVC中实现加载更多