ExtJS与.NET结合开发实例(Grid之数据显示、分页、排序篇)

最近园子里有很多朋友关心ExtJS,我最近写了一个项目管理工具用到ExtJS,我结合.NET写了个关于Grid实现的一个实例供需要的朋友参考。
本实例开发环境是:Windows XP + Sql Server 2005 + IIS6+VS 2008 Beta2(.NET Framework3.5)
实现步骤:
1.取数据源
这里是从数据库里读取数据生产JSON的方式供ExtJS Grid调用.
(1)用Scott Guthrie提供的生产JSON格式的类,这篇文章可以访问:http://weblogs.asp.net/scottgu/archive/2007/10/01/tip,它的译文请访问:http://blog.joycode.com/scottgu/archive/2007/10/10/109268.aspx
建一个类文件JSONHelper.cs,代码如下:

JSONHelper.cs
<!--<br /><br /> <br /><br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /><br /> <a href="http://www.CodeHighlighter.com/" title="http://www.CodeHighlighter.com/">http://www.CodeHighlighter.com/</a><br /><br /> <br /><br /> -->1usingSystem;
2usingSystem.Collections.Generic;
3usingSystem.Text;
4usingSystem.Web.Script.Serialization;
5namespaceWeb.Components
6{
7publicstaticclassJSONHelper
8{
9publicstaticstringToJSON(thisobjectobj)
10{
11JavaScriptSerializerserializer=newJavaScriptSerializer();
12returnserializer.Serialize(obj);
13}

14
15publicstaticstringToJSON(thisobjectobj,intrecursionDepth)
16{
17JavaScriptSerializerserializer=newJavaScriptSerializer();
18serializer.RecursionLimit=recursionDepth;
19returnserializer.Serialize(obj);
20}

21}

22}

23

(2)利用LINQ读取数据记录,关于LINQ方面的文章参考Scott GuthrieLINQ to SQL系列文章
为了方便ExtJS AJAX方式的调用,这里建一个ASPX页面,起名为:ProjectBaseInfo.aspx,代码如下:

ProjectBaseInfo.aspx.cs
<!--<br /><br /> <br /><br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /><br /> <a href="http://www.CodeHighlighter.com/" title="http://www.CodeHighlighter.com/">http://www.CodeHighlighter.com/</a><br /><br /> <br /><br /> -->1usingSystem;
2usingSystem.Data;
3usingSystem.Configuration;
4usingSystem.Collections;
5usingSystem.Linq;
6usingSystem.Web;
7usingSystem.Web.Security;
8usingSystem.Web.UI;
9usingSystem.Web.UI.WebControls;
10usingSystem.Web.UI.WebControls.WebParts;
11usingSystem.Web.UI.HtmlControls;
12usingSystem.Xml.Linq;
13usingBusinessObject.Projects;//dbml文件的引用
14usingSystem.Data.OracleClient;
15usingDatabase;
16usingWeb.Components;
17namespaceWeb.Projects.JsonDataSource
18{
19publicpartialclassProjectBaseInfo:System.Web.UI.Page
20{
21protectedstringstrJsonSource=string.Empty;
22protectedvoidPage_Load(objectsender,EventArgse)
23{
24intstart=int.Parse(Request.Form["start"]+"");//分页需要limit,start是mysql里用的(或取当页开始的记录标识编号)
25intlimit=int.Parse(Request.Form["limit"]+"");//或取每页记录数
26stringsort=Request.Form["sort"]+"";//或取排序方向
27stringdir=Request.Form["dir"]+"";//或取所要排序的字段名
28GetJsonSouceString(start,limit,sort,dir);
29}

30
31privatevoidGetJsonSouceString(intstart,intlimit,stringsort,stringdir)
32{
33ProjectBaseInfoDataContextdb=newProjectBaseInfoDataContext();
34varquery=frompindb.PROJECT_BASE_INFOs
35selectnew{p.PROJECT_NO,p.PROJECT_NAME,p.PROJECT_DEPT_NO,p.PROJECT_MANAGER,p.PROJECT_CURRENT_STATUS,PROJECT_START_DATE=p.PROJECT_START_DATE+"",PROJECT_FINISH_DATE=p.PROJECT_FINISH_DATE+"",PROJECT_REAL_START_DATE=p.PROJECT_REAL_START_DATE+"",PROJECT_REAL_FINISH_DATE=p.PROJECT_REAL_FINISH_DATE+"",p.PROJECT_ALIAS,p.PROJECT_TYPE,p.PROJECT_LEADER,p.PROJECT_MEMO};//类似PROJECT_REAL_FINISH_DATE=p.PROJECT_REAL_FINISH_DATE+"的处理了Grid中日期格式显示的问题
36排序字段和排序方向#region排序字段和排序方向
37if(sort!=""&&dir!="")
38{
39switch(sort)
40{
41case"PROJECT_NO":
42if(dir=="ASC")
43{
44query=query.OrderBy(p=>p.PROJECT_NO);
45}

46else
47{
48query=query.OrderByDescending(p=>p.PROJECT_NO);
49}

50break;
51case"PROJECT_NAME":
52if(dir=="ASC")
53{
54query=query.OrderBy(p=>p.PROJECT_NAME);
55}

56else
57{
58query=query.OrderByDescending(p=>p.PROJECT_NAME);
59}

60break;
61case"PROJECT_DEPT_NO":
62if(dir=="ASC")
63{
64query=query.OrderBy(p=>p.PROJECT_DEPT_NO);
65}

66else
67{
68query=query.OrderByDescending(p=>p.PROJECT_DEPT_NO);
69}

70break;
71case"PROJECT_MANAGER":
72if(dir=="ASC")
73{
74query=query.OrderBy(p=>p.PROJECT_MANAGER);
75}

76else
77{
78query=query.OrderByDescending(p=>p.PROJECT_MANAGER);
79}

80break;
81case"PROJECT_CURRENT_STATUS":
82if(dir=="ASC")
83{
84query=query.OrderBy(p=>p.PROJECT_CURRENT_STATUS);
85}

86else
87{
88query=query.OrderByDescending(p=>p.PROJECT_CURRENT_STATUS);
89}

90break;
91case"PROJECT_START_DATE":
92if(dir=="ASC")
93{
94query=query.OrderBy(p=>p.PROJECT_START_DATE);
95}

96else
97{
98query=query.OrderByDescending(p=>p.PROJECT_START_DATE);
99}

100break;
101case"PROJECT_FINISH_DATE":
102if(dir=="ASC")
103{
104query=query.OrderBy(p=>p.PROJECT_FINISH_DATE);
105}

106else
107{
108query=query.OrderByDescending(p=>p.PROJECT_FINISH_DATE);
109}

110break;
111case"PROJECT_REAL_START_DATE":
112if(dir=="ASC")
113{
114query=query.OrderBy(p=>p.PROJECT_REAL_START_DATE);
115}

116else
117{
118query=query.OrderByDescending(p=>p.PROJECT_REAL_START_DATE);
119}

120break;
121case"PROJECT_REAL_FINISH_DATE":
122if(dir=="ASC")
123{
124query=query.OrderBy(p=>p.PROJECT_REAL_FINISH_DATE);
125}

126else
127{
128query=query.OrderByDescending(p=>p.PROJECT_REAL_FINISH_DATE);
129}

130break;
131default:
132break;
133}

134}

135#endregion

136
137intiCount=query.Count();//所要记录数
138intPageNum=start/limit;//共有页数
139intPageSize=limit;
140query=query.Skip(PageSize*PageNum).Take(PageSize);//当前页记录
141stringJsonSource=query.ToJSON();//当前页记录转成JSON格式
142strJsonSource=@"{""totalCount"":"""+iCount+"";
143strJsonSource=strJsonSource+@""",""data"":"+JsonSource+"}";//Grid的分页区显示所有记录数增加totalCount信息
144}

145}

146}

147


ProjectBaseInfo.aspx中的代码为:

<% @PageLanguage = " C# " AutoEventWireup = " true " CodeBehind = "
ProjectBaseInfo.aspx.cs " Inherits = " Web.Projects.
JsonDataSource.ProjectBaseInfo
" %>
<%= strJsonSource %>

至此,已完成了取数据源。
2.页面客户端
(1)下载ExtJS库,请访问:http://extjs.com/
(2)在你的WEB工程中建一个ExtJS目录。把下载的包里的目录都COPY进来(为了简便起见)。
(3)建一个ProjectLists.html页面,代码如下:

ProjectLists.html
<!--<br /><br /> <br /><br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /><br /> <a href="http://www.CodeHighlighter.com/" title="http://www.CodeHighlighter.com/">http://www.CodeHighlighter.com/</a><br /><br /> <br /><br /> -->1<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<htmlxmlns="http://www.w3.org/1999/xhtml">
3<headrunat="server">
4<title>项目一览表</title>
5<metahttp-equiv="Content-Type"content="text/html;charset=gb2312">
6<linkrel="stylesheet"type="text/css"href="../Resources/css/ext-all.css"/>
7<!--GC-->
8<!--LIBS-->
9<scripttype="text/javascript"src="../Adapter/ext/ext-base.js"></script>
10<!--ENDLIBS-->
11<scripttype="text/javascript"src="../Script/ext-all.js"></script>
12
13<scripttype="text/javascript"src="../Script/GridForProjectLists.js"></script>
14
15<linkrel="stylesheet"type="text/css"href="../CSS/Grid.css"/>
16<linkrel="stylesheet"type="text/css"href="../CSS/Forms.css"/>
17<linkrel="stylesheet"type="text/css"href="../CSS/Combos.css"/>
18<!--CommonStylesfortheProjects-->
19<styletype="text/css">
20body.x-panel
21{}{
22margin-bottom:20px;
23}

24.icon-grid
25{}{
26background-image:url(../Images/icons/grid.png)!important;
27}

28#button-grid.x-panel-body
29{}{
30border:1pxsolid#99bbe8;
31border-top:0none;
32}

33.add
34{}{
35background-image:url(../Images/icons/add.gif)!important;
36}

37.search
38{}{
39background-image:url(../Images/icons/plugin.gif)!important;
40}

41.remove
42{}{
43background-image:url(../Images/icons/delete.gif)!important;
44}

45.save
46{}{
47background-image:url(../Images/icons/save.gif)!important;
48}

49.ext-mb-save
50{}{
51background:transparenturl(../Images/download.gif)no-repeattopleft;
52height:46px;
53}

54
</style>
55</head>
56
57<body>
58</body>
59</html>


(注:请注意JS引用的路径)
(1)新建GridForProjectLists.js文件(这个才是核心
代码如下:

GridForProjectLists.js
<!--<br /><br /> <br /><br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /><br /> <a href="http://www.CodeHighlighter.com/" title="http://www.CodeHighlighter.com/">http://www.CodeHighlighter.com/</a><br /><br /> <br /><br /> -->1/**//*
2*ExtJSLibrary2.0Beta1
3*Copyright(c)2006-2007,ExtJS,LLC.
4*[email protected]
5*
6*http://extjs.com/license
7*/

8Ext.onReady(function(){
9varwin;
10varnewwin;
11Ext.QuickTips.init();
12//createtheDataStore
13vards=newExt.data.GroupingStore({
14//loadusingscripttagsforcrossdomain,ifthedatainonthesamedomainas
15//thispage,anHttpProxywouldbebetter
16proxy:newExt.data.HttpProxy({
17url:'../Projects/JsonDataSource/ProjectBaseInfo.aspx'
18}
),
19
20//createreaderthatreadstheprojectrecords
21reader:newExt.data.JsonReader({
22root:'data',
23totalProperty:'totalCount'
24}
,[
25{name:'PROJECT_NO',type:'string'},
26{name:'PROJECT_NAME',type:'string'},
27{name:'PROJECT_ALIAS',type:'string'},
28{name:'PROJECT_DEPT_NO',type:'string'},
29{name:'PROJECT_MANAGER',type:'string'},
30{name:'PROJECT_LEADER',type:'string'},
31{name:'PROJECT_CURRENT_STATUS',type:'string'},
32{name:'PROJECT_START_DATE',type:'date'},
33{name:'PROJECT_FINISH_DATE',type:'date'},
34{name:'PROJECT_REAL_START_DATE',type:'date'},
35{name:'PROJECT_REAL_FINISH_DATE',type:'date'},
36{name:'PROJECT_MEMO',type:'string'}
37]),
38//groupField:'PROJECT_DEPT_NO',
39remoteSort:true
40}
);
41ds.setDefaultSort('PROJECT_NAME','desc');
42
43//pluggablerenders
44functionrenderProject(value,p,record){
45
46returnString.format(
47'<imgborder=0src="../Images/icons/application_view_list.png"id="btnView_{0}"style="cursor:hand"alt="浏览">&nbsp;&nbsp;<ahref="ProjectDetail.aspx?ProjectNo={0}"target="_blank"><imgborder=0src="../Images/icons/application_view_list.png"style="cursor:hand"alt="编辑"></a>&nbsp;&nbsp;<ahref="ProjectDetail.aspx?ProjectNo={0}"target="_blank"><imgborder=0src="../Images/icons/cross.gif"style="cursor:hand"alt="删除"></a>',
48record.data.PROJECT_NO);
49}

50
51//thecolumnmodelhasinformationaboutgridcolumns
52//dataIndexmapsthecolumntothespecificdatafieldin
53//thedatastore
54varnm=newExt.grid.RowNumberer();
55varsm=newExt.grid.CheckboxSelectionModel();//addcheckboxcolumn
56varcm=newExt.grid.ColumnModel([nm,sm,
57{id:'PROJECT_NO',header:"项目编号",dataIndex:'PROJECT_NO',width:40,align:'center'},
58{header:"项目名称",dataIndex:'PROJECT_NAME',width:100,align:'left'},//,renderer:renderProject},
59{header:"项目简称",dataIndex:'PROJECT_ALIAS',width:50,align:'left'},
60{header:"部门",dataIndex:'PROJECT_DEPT_NO',width:50,align:'center'},
61{header:"项目经理",dataIndex:'PROJECT_MANAGER',width:40,align:'center'},
62{header:"开发经理",dataIndex:'PROJECT_LEADER',width:40,align:'center'},
63{header:"当前状态",dataIndex:'PROJECT_CURRENT_STATUS',width:40,align:'center'},
64{header:"预计开始日期",renderer:Ext.util.Format.dateRenderer('Y-m-d'),dataIndex:'PROJECT_START_DATE',width:50,align:'center'},
65{header:"预计结束日期",renderer:Ext.util.Format.dateRenderer('Y-m-d'),dataIndex:'PROJECT_FINISH_DATE',width:50,align:'center'},
66{header:"实际开始日期",renderer:Ext.util.Format.dateRenderer('Y-m-d'),dataIndex:'PROJECT_REAL_START_DATE',width:50,align:'center'},
67{header:"实际结束日期",renderer:Ext.util.Format.dateRenderer('Y-m-d'),dataIndex:'PROJECT_REAL_FINISH_DATE',width:50,align:'center'},
68{header:"备注",dataIndex:'PROJECT_MEMO',width:50,align:'left'},
69{id:'PROJECT_NO',header:"操作",dataIndex:'PROJECT_NO',width:60,align:'center',renderer:renderProject,sortable:false}
70]);
71
72//hidecolumn
73cm.setHidden(4,!cm.isHidden(4));//隐藏项目简称列
74cm.setHidden(7,!cm.isHidden(7));//隐藏开发经理列
75cm.setHidden(13,!cm.isHidden(13));//隐藏备注列
76//bydefaultcolumnsaresortable
77cm.defaultSortable=true;
78vargdProjects=newExt.grid.GridPanel({
79frame:true,
80collapsible:true,
81animCollapse:false,
82//el:'projects-grid',
83width:965,
84height:530,
85title:'项目一览表',
86iconCls:'icon-grid',
87renderTo:document.body,
88store:ds,
89cm:cm,
90sm:sm,
91trackMouseOver:true,
92loadMask:{msg:'正在加载数据,请稍侯……'},
93//loadMask:true,
94viewConfig:{
95forceFit:true,
96enableRowBody:true,
97getRowClass:function(record,rowIndex,p,ds){
98return'x-grid3-row-collapsed';
99}

100}
,
101view:newExt.grid.GroupingView({
102forceFit:true,
103groupTextTpl:'{text}({[values.rs.length]}条记录)'
104}
),
105bbar:newExt.PagingToolbar({
106pageSize:25,
107store:ds,
108displayInfo:true,
109displayMsg:'当前显示{0}-{1}条记录/{2}条记录',
110emptyMsg:"无显示数据"
111}
),
112//inlinetoolbars
113tbar:[{
114id:'btnAdd',
115text:'新增',
116tooltip:'新增',
117iconCls:'add',
118handler:showAddPanel
119}
,'-',{
120text:'查询',
121tooltip:'查询',
122iconCls:'search'
123}
,'-',{
124text:'批量删除',
125tooltip:'删除',
126iconCls:'remove',
127handler:showDelDialog
128}
]
129
130}
);
131
132}
);


展示成果:
ExtJS与.NET结合开发实例(Grid之数据显示、分页、排序篇)_第1张图片
至此,本文已实现Grid的数据显示、分页、排序的功能。常见的CRUD四个功能的R已完成,接下来,我将提供CUD的功能(如form提交等动作),未完待续……

你可能感兴趣的:(ExtJs)