欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.Net MVC+Data Table实现分页+排序功能的方法

程序员文章站 2023-11-14 13:57:34
本文实例讲述了asp.net mvc+data table实现分页+排序功能的方法。分享给大家供大家参考,具体如下: 实现思路: 使用datatable内置的分页,排序...

本文实例讲述了asp.net mvc+data table实现分页+排序功能的方法。分享给大家供大家参考,具体如下:

实现思路:

使用datatable内置的分页,排序
使用attribute+反射来控制需要排序和显示的字段以及顺序
分离排序和显示逻辑
若要添加搜索逻辑只需要传递搜索的字段到后端即可(js初始化时把"searching": false拿掉)。

view :

@using bcms.businesslogic
@using bcms.businesslogic.models
@model list<buscaptainobj>
<table id="tbldata" class="table table-striped">
  <thead>
    <tr class="data-list">
      <th style="width:10%;">@html.displaynamefor(model => model.first().persno)</th>
      <th style="width:30%;">@html.displaynamefor(model => model.first().personnel_name)</th>
      <th style="width:20%;">@html.displaynamefor(model => model.first().position)</th>
      <th style="width:20%;">@html.displaynamefor(model => model.first().interchange)</th>
      <th style="width:20%;">action</th>
    </tr>
  </thead>
</table>
@section scripts {
  <script type="text/javascript">
     @{
       var columns = datatablehelper.displaycolumns<buscaptainobj>();
     }
    $(document).ready(function () {
      $('#tbldata').datatable({
        "processing": true,
        "serverside": true,
        "searching": false,
        "statesave": true,
        "olanguage": { "sinfofiltered": "" },
        "ajax": {
          "url": @url.action("getjsondata"),
          "type": "get"
        },
        "columns": [
          { "data": "@columns[0]" },
          { "data": "@columns[1]" },
          { "data": "@columns[2]" },
          { "data": "@columns[3]" },
          {
            "data": "@columns[0]",
            "orderable": false,
            "searchable": false,
            "render": function (data, type, full, meta) {
              if (type === 'display') {
                return getdetailbutton("/buscaptain/detail?bcid=", data) + getinfobutton("/telematics?bcid=", data, "performance");
              } else { return data; }
            }
          }
        ],
        "order": [[0, "asc"]]
      });
    });
  </script>
}

controller :

public actionresult getjsondata(int draw, int start, int length)
{
  string search = request.querystring[datatablequerystring.searching];
  string sortcolumn = "";
  string sortdirection = "asc";
  if (request.querystring[datatablequerystring.orderingcolumn] != null)
  {
    sortcolumn = getsortcolumn(request.querystring[datatablequerystring.orderingcolumn]);
  }
  if (request.querystring[datatablequerystring.orderingdir] != null)
  {
    sortdirection = request.querystring[datatablequerystring.orderingdir];
  }
  datatabledata datatabledata = new datatabledata();
  datatabledata.draw = draw;
  int recordsfiltered = 0;
  datatabledata.data = buscaptainservice.instance.searchmybuscaptains(user.identity.name, out recordsfiltered, start, length, sortcolumn, sortdirection, search).data;
  datatabledata.recordsfiltered = recordsfiltered;
  return json(datatabledata, jsonrequestbehavior.allowget);
}
public string getsortcolumn(string sortcolumnno)
{
  var name = datatablehelper.soringcolumnname<buscaptainobj>(sortcolumnno);
  return name;
}
public class datatabledata
{
  public int draw { get; set; }
  public int recordsfiltered { get; set; }
  public list<buscaptainobj> data { get; set; }
}

model :

class xxx{
...
  [displaycolumn(0)]
    [sortingcolumn(0)]
    public int? a { get; set; }
    [displaycolumn(1)]
    [sortingcolumn(1)]
    public string b { get; set; }
...
}

helper class :

public class sortingcolumnattribute : attribute
{
    public int index { get; }
    public sortingcolumnattribute(int index)
    {
      index = index;
    }
}
public class displaycolumnattribute : attribute
{
    public int index { get; }
    public displaycolumnattribute(int index)
    {
      index = index;
    }
}
public static class datatablequerystring
{
    public static string orderingcolumn = "order[0][column]";
    public static string orderingdir = "order[0][dir]";
    public static string searching = "search[value]";
}
public static class datatablehelper
{
    public static ilist<string> displaycolumns<t>()
    {
      var result = new dictionary<int, string>();
      var props = typeof(t).getproperties();
      foreach (var propertyinfo in props)
      {
        var propattr =
          propertyinfo
            .getcustomattributes(false)
            .oftype<displaycolumnattribute>()
            .firstordefault();
        if (propattr != null)
        {
          result.add(propattr.index,propertyinfo.name);
        }
      }
      return result.orderby(x => x.key).select(x => x.value).tolist();
    }
    public static string soringcolumnname<t>(string columnindex)
    {
      int index;
      if (!int.tryparse(columnindex, out index))
      {
        throw new argumentoutofrangeexception();
      }
      return soringcolumnname<t>(index);
    }
    public static string soringcolumnname<t>(int index)
    {
      var props = typeof(t).getproperties();
      foreach (var propertyinfo in props)
      {
        var propattr =
          propertyinfo
            .getcustomattributes(false)
            .oftype<sortingcolumnattribute>()
            .firstordefault();
        if (propattr != null && propattr.index == index)
        {
          return propertyinfo.name;
        }
      }
      return "";
    }
}

query:

...
var query = context.buscaptains
            .where(x => ...)
            .orderbyex(sortdirection, sortfield)
            .skip(start)
            .take(pagesize);
...

linq helper :

...
public static iqueryable<t> orderbyex<t>(this iqueryable<t> q, string direction, string fieldname)
    {
      try
      {
        var customproperty = typeof(t).getcustomattributes(false).oftype<columnattribute>().firstordefault();
        if (customproperty != null)
        {
          fieldname = customproperty.name;
        }
        var param = expression.parameter(typeof(t), "p");
        var prop = expression.property(param, fieldname);
        var exp = expression.lambda(prop, param);
        string method = direction.tolower() == "asc" ? "orderby" : "orderbydescending";
        type[] types = new type[] {q.elementtype, exp.body.type};
        var mce = expression.call(typeof(queryable), method, types, q.expression, exp);
        return q.provider.createquery<t>(mce);
      }
      catch (exception ex)
      {
        _log.errorformat("error form orderbyex.");
        _log.error(ex);
        throw ;
      }
    }
...

更多关于asp.net相关内容感兴趣的读者可查看本站专题:《asp.net优化技巧总结》、《asp.net字符串操作技巧汇总》、《asp.net操作xml技巧总结》、《asp.net文件操作技巧汇总》、《asp.net ajax技巧总结专题》及《asp.net缓存操作技巧总结》。

希望本文所述对大家asp.net程序设计有所帮助。