- 浏览: 679256 次
文章分类
最新评论
使用Dynamic LINQ实现Ext Grid的远程排序
<!--[if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:PunctuationKerning /> <w:DrawingGridVerticalSpacing>7.8 磅</w:DrawingGridVerticalSpacing> <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery> <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery> <w:ValidateAgainstSchemas /> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:SpaceForUL /> <w:BalanceSingleByteDoubleByteWidth /> <w:DoNotLeaveBackslashAlone /> <w:ULTrailSpace /> <w:DoNotExpandShiftReturn /> <w:AdjustLineHeightInTable /> <w:BreakWrappedTables /> <w:SnapToGridInCell /> <w:WrapTextWithPunct /> <w:UseAsianBreakRules /> <w:DontGrowAutofit /> <w:UseFELayout /> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--><!--[if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="156"> </w:LatentStyles> </xml><![endif]--> <!--[if gte mso 10]> <mce:style><! /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} table.MsoTableGrid {mso-style-name:网格型; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; border:solid windowtext 1.0pt; mso-border-alt:solid windowtext .5pt; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-border-insideh:.5pt solid windowtext; mso-border-insidev:.5pt solid windowtext; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; mso-pagination:none; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} --> <!--[endif]-->
要实现Ext Grid的远程排序其实很简单,只要修改查询语句的排序关键字就可以了,但是,如果你的项目是使用Linq进行开发的,会发现动态修改排序关键字并不是那么容易的事,解决办法就是使用LINQ Dynamic Query Library。LINQ Dynamic Query Library是一个很实用很强大的库函数,通过该库,可以轻松实现一些需要通过动态参数实现的Linq查询。
本文将通过一个实例演示如何使用LINQ Dynamic Query Library实现Ext Grid的远程排序。
LINQ Dynamic Query Library可以在VS2008的例程里找到,也可以从以下链接下载:
- VB Dynamic Query Library (included in the /Language Samples/LINQ Samples/DynamicQuery directory)
- C# Dynamic Query Library (included in the /LinqSamples/DynamicQuery directory)
本例子将使用SQL Server的“NORTHWND”样例数据库。Ext Grid显示的是Employees表的数据。
以下是客户端的完整代码:
<html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" xmlns="" /> <link rel="stylesheet" type="text/css" href="lib/ext/resources/css/ext-all.css" /> <link rel="stylesheet" type="text/css" href="css/application.css" /> </head> <script type="text/javascript" src="lib/ext/ext-base.js"></script> <script type="text/javascript" src="lib/ext/ext-all.js"></script> <script type="text/javascript" src="lib/ext/locale/ext-lang-zh_CN.js"></script> <body scroll="no"> <div id="loading-mask"></div> <div id="loading"> <div class="loading-indicator"><img alt="" src="lib/ext/resources/images/default/shared/large-loading.gif" width="32" height="32" style="margin-right:8px;" align="absmiddle"/>正在加载...</div> </div> <script type="text/javascript">
var app={}
Ext.onReady(function(){ Ext.BLANK_IMAGE_URL='lib/ext/resources/images/default/s.gif'; Ext.QuickTips.init(); Ext.form.Field.prototype.msgTarget = 'side'; Ext.Msg.minWidth=300;
app.store=new Ext.data.Store({ url:'employees_action.ashx?act=list', baseParams:{}, reader:new Ext.data.JsonReader({ totalProperty: "results", root:"rows", id:"id" },[{name: 'id',type:'int'},{name:'lastname'},{name:'firstname'}, {name:'title'},{name:'titleofcourtesy'},{name:'city'}, {name:'address'},{name:'region'},{name:'postalcode'},{name:'homephone'},{name:'country'}, {name:'birthdate',type: 'date',dateFormat:'Y-m-d'}, {name:'hiredate',type: 'date',dateFormat:'Y-m-d'} ]), remoteSort: true }) //store
app.pageToolbar=new Ext.PagingToolbar({ pageSize:3,displayInfo:true,store:app.store });
app.grid=new Ext.grid.GridPanel({layout:'fit', store:app.store, autoExpandColumn:2,tbar:app.pageToolbar, columns: [ {id:'id',header: "ID",width:80,dataIndex:'id',sortable: true}, {header: "FirstName",width:80, dataIndex:'firstname',sortable: true}, {header: "LastName",width:80, dataIndex:'lastname',sortable: true}, {header: "Title",width:80, dataIndex:'title',sortable: true}, {header: "Title of Courtesy",width:80, dataIndex:'titleofcourtesy',sortable: true}, {header: "City",width:80, dataIndex:'city',sortable: true}, {header: "Region",width:80, dataIndex:'region',sortable: true}, {header: "Country",width:80, dataIndex:'country',sortable: true}, {header: "Postalcode",width:80, dataIndex:'postalcode',sortable: true}, {header: "Homephone",width:80, dataIndex:'homephone',sortable: true}, {header: "Birthdate", width: 120,dataIndex:'birthdate',sortable: true,renderer:Ext.util.Format.dateRenderer('Y-m-d')}, {header: "Hiredate", width: 120,dataIndex:'hiredate',sortable: true,renderer:Ext.util.Format.dateRenderer('Y-m-d')} ] })
var viewport = new Ext.Viewport({layout:'fit',items:[app.grid]});
app.store.load();
setTimeout(function(){ Ext.get('loading').remove(); Ext.get('loading-mask').fadeOut({remove:true}); }, 250);
})//onReady </script> </body> </html> |
代码很简单,定义了一个Store、PagetoolBar和Grid。因为Employees表数据只有9条,所以设置了每页3条数据。在Store定义中将remoteSort设置为true,说明数据要实现远程排序。Grid的每一列都将sortable属性设置为true,说明都可以通过单击Grid的列标题实现排序。
以下是服务器端的完整代码:
<%@ WebHandler Language="C#" Class="employees_action" Debug="true" %>
using System; using System.Web; using System.Linq; using System.Linq.Dynamic; using System.Collections; using System.Collections.Generic; using System.Web.Security; using LitJson;
public class employees_action : IHttpHandler {
public void ProcessRequest (HttpContext context) { string action = context.Request.Params["act"]; string outputStr = ""; if (action == null) action = ""; switch (action.ToLower()) { case "list": outputStr = List(context); break; default: outputStr = HDQ.Functions.WriteJsonResult(false, "错误的操作类型!"); break; } context.Response.ContentType = "text/javascript"; context.Response.Write(outputStr); }
public bool IsReusable { get { return false; } }
private string List(HttpContext context) { int limit=0; int.TryParse(context.Request.Params["limit"], out limit); if (limit == 0) limit = 3; int start=0; int.TryParse(context.Request.Params["start"], out start); string orderColumn = context.Request.Params["sort"]; string orderBy = context.Request.Params["dir"] == "ASC" ? "" : "descending"; switch (orderColumn) { case "id": orderColumn = "EmployeeID"; break; case "lastname": orderColumn = "LastName"; break; case "firstname": orderColumn = "FirstName"; break; case "title": orderColumn = "Title"; break; case "titleofcourtesy": orderColumn = "TitleOfCourtesy"; break; case "birthdate": orderColumn = "BirthDate"; break; case "hiredate": orderColumn = "HireDate"; break; case "address": orderColumn = "Address"; break; case "city": orderColumn = "City"; break; case "region": orderColumn = "Region"; break; case "postalcode": orderColumn = "PostalCode"; break; case "country": orderColumn = "Country"; break; case "homephone": orderColumn = "HomePhone"; break; default: orderColumn = "EmployeeID"; break; } DBDemosDataContext dc = new DBDemosDataContext(); int recordCount=0; JsonWriter jw = new JsonWriter(); jw.WriteObjectStart(); jw.WritePropertyName("rows"); jw.WriteArrayStart(); recordCount = dc.Employees.Count(); if (start > recordCount) start = 0; var q=dc.Employees.OrderBy(orderColumn + " " + orderBy).Skip(start).Take(limit); foreach (var c in q) { jw.WriteObjectStart(); jw.WritePropertyName("id"); jw.Write(c.EmployeeID); jw.WritePropertyName("firstname"); jw.Write(c.FirstName); jw.WritePropertyName("lastname"); jw.Write(c.LastName); jw.WritePropertyName("title"); jw.Write(c.Title); jw.WritePropertyName("titleofcourtesy"); jw.Write(c.TitleOfCourtesy); jw.WritePropertyName("address"); jw.Write(c.Address); jw.WritePropertyName("city"); jw.Write(c.City); jw.WritePropertyName("region"); jw.Write(c.Region); jw.WritePropertyName("country"); jw.Write(c.Country); jw.WritePropertyName("postalcode"); jw.Write(c.PostalCode); jw.WritePropertyName("homephone"); jw.Write(c.HomePhone); jw.WritePropertyName("birthdate"); jw.Write(c.BirthDate == null ? "" : Convert.ToDateTime(c.BirthDate).ToString("yyyy-MM-dd")); jw.WritePropertyName("hiredate"); jw.Write(c.HireDate == null ? "" : Convert.ToDateTime(c.HireDate).ToString("yyyy-MM-dd")); jw.WriteObjectEnd(); }
jw.WriteArrayEnd(); jw.WritePropertyName("results"); jw.Write(recordCount.ToString()); jw.WriteObjectEnd(); return jw.ToString(); }
} |
代码中ProcessRequest方法根据提交的参数action执行对应的方法。本文主要是执行List方法。
在List方法的开头首先获取了客户端提交的几个参数,参数对应的说明请看下表:
参数 |
说明 |
limit |
每页总数,本例子是3 |
start |
提取数据开始位置 |
sort |
要排序的列 |
dir |
排序顺序 |
获取数据后需要对排序的列名和顺序做一下转换,以下语句就是实现排序顺序的转换:
string orderBy = context.Request.Params["dir"] == "ASC" ? "" : "descending"; |
列名的转换则通过switch语句实现。如果在客户端定义的列名与数据库的真实列名相同,也可以不实施转换。不过,出于安全考虑,建议无论如何,还是要实行转换。
转换完成后,就可以定义查询语句了,相当的简单:
var q=dc.Employees.OrderBy(orderColumn + " " + orderBy).Skip(start).Take(limit); |
将列名变量和顺序变量组合成字符串作为OrderBy方法的参数就可以了。LINQ Dynamic Query Library会自动重新生成Linq语句执行。
后面的代码就是将查询结果组合成Json格式数据输出。
如果不使用LINQ Dynamic Query Library,远程排序的实现最直接的方法就是使用switch语句,根据提交的列和排序顺序写不同的Linq语句,就不如本例的代码那么简洁了。
以下是本例程的代码下载地址:
http://download.csdn.net/source/1212462
相关推荐
ExtJs+WCF+LINQ实现分页Grid
Dynamic LINQ to NHibernate
个人开发的采用三层架构+mvc+linq+ext的记账系统。对于学习mvc框架或是linq to sql技术或是ext,或是三层框架架构都是很好的例子。数据库用的是sql2008,如果没装sql 2008的朋友也没关系,本人提供了表创建的SQL文件...
Linq排序
使用linq实现rss聚合.
此代码类很好的用linq技术实现分页,在这将他分享给各位有需要的人。
Kendo.DynamicLinqCore通过Dynamic Linq for .Net Core App(1.x〜3.x)实现服务器分页,过滤,排序,分组和聚合到Kendo UI。 先决条件 .Net核心1〜2 没有任何 .Net核心3 您必须将自定义...
使用linq实现对SQL Server数据库的增加、删除、更改、查询,程序简单易懂,非常适合初学者。
System.Linq.Dynamic.dll实现了C#中动态的linq查询,引用之后可以以字符串的形式使用linq。
linq实现OA项目源码,这个是我朋友的哈。。我分享出来。经过同意了哈!
linq to sql实现分层与gridview使用实现增删改,适合新手做三层项目开发,快速入门
基于XML + LINQ 实现的Dynamic Silverlight 控件源码例子。
vs2015实现功能,读取本地json文件用来当作数据源。使用linq语法分页查询显示。 有兴趣的可以拿去参考。 dgv.DataSource = groups.Skip(pageIndex).Take(pageSize).ToList();
.net linq动态组合查询条件及排序,让linq像ado.net那样动态组合条件查询
在C#3.0中针对SQL数据库动态创建Linq查询的框架,该数据库自动填充用于WPF绑定的ObservableCollection还包括Observable EntitySet 包装器,用于将EntitySet绑定到WPF控件ItemsSource
ASP.NET结合ExtJs+WCF+LINQ实现的分页Grid列表,一个很不错的学习ASP.NET/AJAX的参考实例,而且如果你的程序用了此分页代码,也会增色不少。
dynamic-linq-query-builder是一个小型库,允许任何.Net框架类集合在运行时动态过滤。 功能(v1.2.0) 从任何集合和过滤器组合生成IQueryable 可以根据需要对多个字段进行复杂的分组查询 通过点表示法支持嵌套...
linq实现简单图书管理系统 通过Linq实现数据库的简单添加、修改和列表读取