MVC + bootstrap + Draper uses pagedlist.mvc to support multi query criteria paging


A few days ago, I did a small project and used MVC + bootstrap. In the past, paging was done by asynchronously loading MVC partial views, because this is a small project, just a little casually. For general list pages, query conditions are indispensable. Let’s share the experience of Draper + pagedlist.mvc in supporting multi query condition paging.

In MVC, we are generally used to using a strongly typed model. We build this model by analyzing the display page of orders.

1. Model of query parameter

public class OrderQueryParamModel
    /// <summary>
    ///Order No
    /// </summary>
    public string OrderNo { get; set; }
    /// <summary>
    ///Customer name
    /// </summary>
    public string CustomerName { get; set; }

2. Orders paging data model

Pagedlist provides a staticpagedlist < T > generic class to encapsulate data. (look at the source code of staticpagedlist. It is very convenient to use. Just initialize the T-type data subset, PageNumber, PageSize and totalcount.

public StaticPagedList(IEnumerable<T> subset, IPagedList metaData) : this(subset, metaData.PageNumber, metaData.PageSize, metaData.TotalItemCount)

3. Overall model of orders display page

public class OrderViewModel
    public OrderQueryParamModel QueryModel { get; set; }
    public PagedList.StaticPagedList<OrderModel> OrderList { get; set; } 

OK, let’s see how to fill the orderviewmodel with data in the controller

 public ActionResult List(OrderViewModel orderViewModel, int page = 1)
      var pagesize = 10;
      var count = 0;
      var orders = _orderService.GetOrders(page, pagesize, model.QueryModel, ref count);
      orderViewModel.OrderList = new StaticPagedList<OrderModel>(orders, page, pagesize, count);
      return View(orderViewModel);

The code in the controller is very simple. It receives two parameters from the post. Orderviewmodel: contains the query parameter model, and page: the current page defined by pagedlist.

By the way, let’s take a look at the getorders () method. In order to save trouble, I’m too lazy to write stored procedures. I directly use the draper’s querymomple. It feels very powerful.

 public List<OrderModel> GetOrders(int pageindex, int pagesize, OrderQueryParamModel query, ref int count)
      var orders = new List<OrderModel>();
      var whereStr = string.Empty;
      if (query != null)
        if (!string.IsNullOrEmpty(query.CustomerName))
          whereStr += string.Format(" and CustomerName like '%{0}%' ", query.CustomerName);
      var cmd = string.Format(@"SELECT COUNT(*) FROM [Orders] WHERE 1=1 {0};
            SELECT * FROM (
            SELECT *, row_number() OVER (ORDER BY orderId DESC ) AS [row] 
                 FROM [Orders] WHERE 1=1 {0} )t
            WHERE t.row >@indexMin AND t.row<[email protected]", whereStr);
      using (IDbConnection conn = BaseDBHelper.GetConn())
        using (var multi = conn.QueryMultiple(cmd, 
          new { indexMin = (pageindex - 1) * pagesize, indexMax = pageindex * pagesize }))
          count = multi.Read<int>().SingleOrDefault();
          orders = multi.Read<OrderModel>().ToList();
      return orders;

Note that the order of multi. Read must be the same as that of the data set queried by SQL.

Well, the data has been obtained so happily. Finally, let’s take a look at the key front-end data display.

1. First add a reference in the view

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

2. Create a form for the query

  @using (Html.BeginForm("List", "Order", FormMethod.Post, new { id = "OrderForm", @class = "form-horizontal" }))
    @HTML. Raw ("customer name:") @ HTML. Textboxfor (M = > m.querymodel. Customername)
    @HTML. Raw ("Order No.:) @ HTML. Textboxfor (M = > m.querymodel. OrderNo)
    < button type = "submit" > query < / button >
    //Yi, why do you use this? It will be explained later
    <input type="hidden" name="page" value="1" />

3. Binding data

      < th > order No. < / th >
      < th > Customer Name < / th >
      < th > mobile number < / th >      
      < th > quantity of goods < / th >
      < th > order amount < / th >
      < th > order time < / th >
    @foreach (var item in Model.OrderList)

4. Bind paging plug-in data

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

OK, everything is done. After running, you will find that the links generated by paging navigation are in the form of “/ order / list / 2”, which cannot support us to pass other query parameters to the controller.

Let’s change our thinking. Why not put the parameter page in the form form?   Remember that there is a hidden input with name = page in our form?

 $(function () {
    $(".pagination > li > a").click(function () {
      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;

Through this JS, we directly invalidate the a tag of the original page, get its page value and put it in the form, and then directly trigger the submit() of the form, which meets our general query business requirements.

The above is what Xiaobian introduced to you. MVC + bootstrap + Draper uses pagedlist.mvc to support multi query criteria paging. I hope it will be helpful to you. If you have any questions, please leave us a message and Xiaobian will reply to you in time!

Recommended Today

Beautify your code VB (VBS) code formatting implementation code

However, does have many new functions that VB6 does not have. The automatic typesetting of code is one, which is the function we want to realize today – VB code formatting.Let’s look at the effect: Before formatting: Copy codeThe code is as follows: For i = 0 To WebBrowser1.Document.All.length – 1 If WebBrowser1.Document.All(i).tagName = […]