MVC+Bootstrap+Drapper使用PagedList.Mvc支持多查询条件分页

2019-05-25 19:45:03王冬梅

这里要注意下的是,multi.Read的顺序必须和Sql查询出来的数据集合顺序一样。

好了,数据就这么愉快的获取了,最后来看看关键的前端数据展示吧。

1.首先在View中添加引用

@using PagedList.Mvc;
@using PagedList;
@model Models.OrderViewModel

2.为查询创建一个表单

<div class="page-header">
  @using (Html.BeginForm("List", "Order", FormMethod.Post, new { id = "OrderForm", @class = "form-horizontal" }))
  {
    @Html.Raw("客户名称:") @Html.TextBoxFor(m => m.QueryModel.CustomerName)
    @Html.Raw("订单编号:") @Html.TextBoxFor(m => m.QueryModel.OrderNo)
    <button type="submit" class="btn btn-purple btn-sm">查询</button>
    //咿,这个干吗用的?后面会解释
    <input type="hidden" name="page" value="1" />
  }
</div>

3.绑定数据

<table class="table loading table-bordered margin-top-5 margin-bottom-5">
  <thead>
    <tr>
      <th>订单编号</th>
      <th>客户名称</th>
      <th>手机号码</th>      
      <th>商品数量</th>
      <th>订单金额</th>
      <th>下单时间</th>
    </tr>
  </thead>
  <tbody>
    @foreach (var item in Model.OrderList)
    {
      <tr>
        <td>@item.orderNo</td>
        <td>@item.customerName</td>
        <td>@item.customerMobile</td>
        <td>@item.productQuantity</td>
        <td>@item.orderAmount</td>
        <td>@item.orderCreateTime</td>
      </tr>
    }
  </tbody>
</table>

4.绑定分页插件数据

@if (Model.OrderList != null&&Model.OrderList.Any())
{
  <div class="pagedList" style="margin:0 auto;text-align:center">
    @Html.PagedListPager(Model.OrderList, page => Url.Action("List", new { page }), PagedListRenderOptions.Classic)
  </div>
}

OK,一切搞定了,运行你会发现,分页导航生成的链接都是 "/Order/List/2" 这种形式,无法支持我们把其他查询参数也传递到Controller。

我们换一个思路,为什么不把page这个参数放到form表单去了?  还记得我们form中有一个name=page 的hidden input吧?

 $(function () {
    $(".pagination > li > a").click(function () {
      event.preventDefault();
      var index = $(this).html();
      if (index == '»') {
        index = parseInt($(".pagination > li[class=active] > a").html()) + 1;
      }
      if (index == '«') {
        index = parseInt($(".pagination > li[class=active] > a").html()) - 1;
      }
      if (index < 1) return;
      $("input[name=page]").val(index);
      $("#OrderForm").submit();
    });
  });

通过这段JS,直接把原来分页的a标签作废了,获取他的page值放到了form中,然后直接触发form的submit(),这样就满足了我们一般的查询业务需求。