. Net Mvc+data Table Implementation of pagination + sorting tutorial

Source: Internet
Author: User
Tags bcms
This article mainly introduces the method of ASP. NET Mvc+data table to realize the paging + sorting function, and analyzes the related operation skills of ASP, such as data query, sorting and pagination display based on MVC architecture, and the friends can refer to

This article describes the method of ASP. NET Mvc+data table to implement the paging + sorting function. Share to everyone for your reference, as follows:

Implementation ideas:

Using the DataTable built-in pagination, sort
Use attribute+ reflection to control which fields and order you want to sort and display
Separating sorting and display logic
To add search logic you only need to pass the search field to the backend (JS initializes the "searching": false to take off).

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" &G     T     @{var columns = datatablehelper.displaycolumns<buscaptainobj> ();        } $ (document). Ready (function () {$ (' #tblData '). DataTable ({"Processing": true, "serverside": true,      "Searching": false,  "Statesave": True, "Olanguage": {"sinfofiltered": ""}, "Ajax": {"url": @Url. Action ("Getjsondat A ")," 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) + Getinfob              Utton ("/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[datatablequerystrin  G.searching];  String sortcolumn = "";  String sortdirection = "ASC"; if (request.querystring[datatablequerystring.orderingcolumn]! = null) {SortColumn = Getsortcolumn (Request.QueryStrin  G[datatablequerystring.orderingcolumn]); } if (Request.querystring[datatablequerystring.orderingdir]! = null) {SortDirection = Request.querystring[datatableq  Uerystring.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&LT;BUSCAPTAINOBJ&Gt; (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. (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); The 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"?        "By": "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; }    }...
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.