ASP.Net MVC+Data Table实现分页+排序功能的方法
本文实例讲述了ASP.NetMVC+DataTable实现分页+排序功能的方法。分享给大家供大家参考,具体如下:
实现思路:
使用datatable内置的分页,排序
使用attribute+反射来控制需要排序和显示的字段以及顺序
分离排序和显示逻辑
若要添加搜索逻辑只需要传递搜索的字段到后端即可(js初始化时把"searching":false拿掉)。
View:
@usingBCMS.BusinessLogic @usingBCMS.BusinessLogic.Models @modelList@sectionscripts{ @Html.DisplayNameFor(model=>model.First().PersNo) @Html.DisplayNameFor(model=>model.First().Personnel_Name) @Html.DisplayNameFor(model=>model.First().Position) @Html.DisplayNameFor(model=>model.First().Interchange) Action @{ varcolumns=DataTableHelper.DisplayColumns (); } $(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'){ returnGetDetailButton("/BusCaptain/Detail?bcId=",data)+GetInfoButton("/Telematics?bcId=",data,"Performance"); }else{returndata;} } } ], "order":[[0,"asc"]] }); }); }
Controller:
publicActionResultGetJsonData(intdraw,intstart,intlength) { stringsearch=Request.QueryString[DataTableQueryString.Searching]; stringsortColumn=""; stringsortDirection="asc"; if(Request.QueryString[DataTableQueryString.OrderingColumn]!=null) { sortColumn=GetSortColumn(Request.QueryString[DataTableQueryString.OrderingColumn]); } if(Request.QueryString[DataTableQueryString.OrderingDir]!=null) { sortDirection=Request.QueryString[DataTableQueryString.OrderingDir]; } DataTableDatadataTableData=newDataTableData(); dataTableData.draw=draw; intrecordsFiltered=0; dataTableData.data=BusCaptainService.Instance.SearchMyBuscaptains(User.Identity.Name,outrecordsFiltered,start,length,sortColumn,sortDirection,search).Data; dataTableData.recordsFiltered=recordsFiltered; returnJson(dataTableData,JsonRequestBehavior.AllowGet); } publicstringGetSortColumn(stringsortColumnNo) { varname=DataTableHelper.SoringColumnName(sortColumnNo); returnname; } publicclassDataTableData { publicintdraw{get;set;} publicintrecordsFiltered{get;set;} publicList data{get;set;} }
Model:
classXXX{ ... [DisplayColumn(0)] [SortingColumn(0)] publicint?A{get;set;} [DisplayColumn(1)] [SortingColumn(1)] publicstringB{get;set;} ... }
Helperclass:
publicclassSortingColumnAttribute:Attribute { publicintIndex{get;} publicSortingColumnAttribute(intindex) { Index=index; } } publicclassDisplayColumnAttribute:Attribute { publicintIndex{get;} publicDisplayColumnAttribute(intindex) { Index=index; } } publicstaticclassDataTableQueryString { publicstaticstringOrderingColumn="order[0][column]"; publicstaticstringOrderingDir="order[0][dir]"; publicstaticstringSearching="search[value]"; } publicstaticclassDataTableHelper { publicstaticIListDisplayColumns () { varresult=newDictionary (); varprops=typeof(T).GetProperties(); foreach(varpropertyInfoinprops) { varpropAttr= propertyInfo .GetCustomAttributes(false) .OfType () .FirstOrDefault(); if(propAttr!=null) { result.Add(propAttr.Index,propertyInfo.Name); } } returnresult.OrderBy(x=>x.Key).Select(x=>x.Value).ToList(); } publicstaticstringSoringColumnName (stringcolumnIndex) { intindex; if(!int.TryParse(columnIndex,outindex)) { thrownewArgumentOutOfRangeException(); } returnSoringColumnName (index); } publicstaticstringSoringColumnName (intindex) { varprops=typeof(T).GetProperties(); foreach(varpropertyInfoinprops) { varpropAttr= propertyInfo .GetCustomAttributes(false) .OfType () .FirstOrDefault(); if(propAttr!=null&&propAttr.Index==index) { returnpropertyInfo.Name; } } return""; } }
Query:
... varquery=context.BusCaptains .Where(x=>...) .OrderByEx(sortDirection,sortField) .Skip(start) .Take(pageSize); ...
LINQHelper:
... publicstaticIQueryableOrderByEx (thisIQueryable q,stringdirection,stringfieldName) { try { varcustomProperty=typeof(T).GetCustomAttributes(false).OfType ().FirstOrDefault(); if(customProperty!=null) { fieldName=customProperty.Name; } varparam=Expression.Parameter(typeof(T),"p"); varprop=Expression.Property(param,fieldName); varexp=Expression.Lambda(prop,param); stringmethod=direction.ToLower()=="asc"?"OrderBy":"OrderByDescending"; Type[]types=newType[]{q.ElementType,exp.Body.Type}; varmce=Expression.Call(typeof(Queryable),method,types,q.Expression,exp); returnq.Provider.CreateQuery (mce); } catch(Exceptionex) { _log.ErrorFormat("errorformOrderByEx."); _log.Error(ex); throw; } } ...
更多关于asp.net相关内容感兴趣的读者可查看本站专题:《asp.net优化技巧总结》、《asp.net字符串操作技巧汇总》、《asp.net操作XML技巧总结》、《asp.net文件操作技巧汇总》、《asp.netajax技巧总结专题》及《asp.net缓存操作技巧总结》。
希望本文所述对大家asp.net程序设计有所帮助。