Using jQuery DataTables to realize data paging display function in asp.net MVC

Time:2021-7-28

1. The method code in the controller is as follows:

Since the stored procedure in the method does not have paging parameters, there is still room for further optimization.

/// <summary>
    ///Get the list of measuring points
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public JsonResult GetMeasurePointList(string TreeID, string TreeType, int sEcho, int iDisplayStart, int iDisplayLength)
    {
      DataTable dtResult = new DataTable();
      string sql = string.Format("EXEC P_GET_ZXJG_TagList '{0}','{1}'", TreeID, TreeType);
      dtResult = QuerySQL.GetDataTable(sql);
      dtResult.Columns.Add("XuHao", typeof(string));
      dtResult.Columns.Add("StrValueTime", typeof(string));
      for (int i = 0; i < dtResult.Rows.Count; i++)
      {
        dtResult.Rows[i]["XuHao"] = (i + 1).ToString();
        dtResult.Rows[i]["StrValueTime"] = Convert.ToDateTime(dtResult.Rows[i]["F_ValueTime"]).ToString("yyyy-MM-dd HH:mm:ss");
      }
      int iTotalRecords = 0;
      int iTotalDisplayRecords = 0;
      List<DataRow> queryList = dtResult.AsEnumerable().ToList();
      iTotalRecords = queryList.Count();
      queryList = queryList.Skip(iDisplayStart).Take(iDisplayLength).ToList();
      iTotalDisplayRecords = queryList.Count();
      var temp = from p in queryList
            select new
            {
              XuHao = p.Field<string>("XuHao").ToString(),
              F_Description = p.Field<string>("F_Description").ToString(),
              StrValueTime = p.Field<string>("StrValueTime").ToString(),
              F_Value = p.Field<decimal>("F_Value").ToString(),
              F_Unit = p.Field<string>("F_Unit").ToString(),
              F_AlmLow = p.Field<decimal>("F_AlmLow").ToString(),
              F_AlmUp = p.Field<decimal>("F_AlmUp").ToString()
            };
      return Json(new
        {
          draw = sEcho,
          recordsFiltered = iTotalRecords,
          recordsTotal = iTotalDisplayRecords,
          data = temp.ToList()
        }, JsonRequestBehavior.AllowGet);
    }

2. The code in the cshtml view page is as follows:

function InitData() {
    var dataTable = $('#tbMeasurePointList').DataTable({
      "scrollY": "hidden",
      "scrollCollapse": false,
      "dom": 'tr<"bottom"lip><"clear">',
      language: {
        Lengthmenu: '', // the page size in the upper left corner is displayed.
        Search: '< span > Search: < / span >' // the search text in the upper right corner can write HTML tags
        Loadingrecords: 'data loading...',
        paginate: {
          //Pagination style content.
          Previous: "previous page",
          Next: "next page",
          first: "",
          last: ""
        },
        Zerorecords: "no data yet", // when the content of table tbody is empty, the content of tbody.
        //The following three constitute the lower left corner of the overall content.
        Info: "< span class ='pagesstyle '> total < span class ='recordsstyle' >_ TOTAL_  Article, total_ PAGES_ </ Span > page, currently displayed_ START_ -- _ END_  Records < / span > ", // the information in the lower left corner shows that capitalized words are keywords. Initial_ MAX_  strip 
        Infoempty: "0 records", // the display in the lower left corner when the filter is empty.
        Infofiltered: "" // filtering prompt in the lower left corner after filtering,
      },
      "lengthChange": false,
      "ordering": false,
      "iDisplayLength": 10,
      "searching": false,
      Destroy: true, // cannot reinitialize datatable to solve the problem of reloading table contents 
      "serverSide": true,
      "sAjaxSource": "@Url.Action("GetMeasurePointList", "OnlineMonitor")",
      "fnServerData": function (sSource, aoData, fnCallback) {
        aoData.push({ "name": "TreeID", "value": $("#hidTreeID").val() });
        aoData.push({ "name": "TreeType", "value": $("#hidTreeType").val() });
        $.ajax({
          "dataType": 'json',
          "type": "POST",
          "url": sSource,
          "data": aoData,
          "success": fnCallback
        });
      },
      "aoColumns": [
        { "mDataProp": "XuHao", "width": "50" },
        { "mDataProp": "F_Description", "width": "400" },
        { "mDataProp": "StrValueTime", "width": "200" },
        { "mDataProp": "F_Value", "width": "100" },
        { "mDataProp": "F_Unit", "width": "100" },
        { "mDataProp": "F_AlmLow", "width": "100" },
        { "mDataProp": "F_AlmUp", "width": "100"}
      ],
      "createdRow": function (row, data, index) {
        $(row).children('td').eq(0).attr('style', 'text-align: center;');
        $(row).children('td').eq(1).attr('style', 'text-align: left;');
        $(row).children('td').eq(2).attr('style', 'text-align: center;');
        $(row).children('td').eq(3).attr('style', 'text-align: right;');
        $(row).children('td').eq(4).attr('style', 'text-align: center;');
        $(row).children('td').eq(5).attr('style', 'text-align: right;');
        $(row).children('td').eq(6).attr('style', 'text-align: right;');
      }
    });
  }

3. The actual display effect is shown in the following figure:

The above is what Xiaobian introduced to you. In asp.net MVC, jQuery DataTables is used to realize data paging display. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support to the developeppaer website!

Recommended Today

VBS obtains the operating system and its version number

VBS obtains the operating system and its version number ? 1 2 3 4 5 6 7 8 9 10 11 12 ‘************************************** ‘*by r05e ‘* operating system and its version number ‘************************************** strComputer = “.” Set objWMIService = GetObject(“winmgmts:” _  & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”) Set colOperatingSystems = objWMIService.ExecQuery _  (“Select * from […]