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,代码如下:

 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4using System.Web.Script.Serialization;
 5namespace Web.Components
 6{
 7    public static class JSONHelper
 8    {
 9        public static string ToJSON(this object obj)
10        {
11            JavaScriptSerializer serializer = new JavaScriptSerializer();
12            return serializer.Serialize(obj);
13        }

14
15        public static string ToJSON(this object obj, int recursionDepth)
16        {
17            JavaScriptSerializer serializer = new JavaScriptSerializer();
18            serializer.RecursionLimit = recursionDepth;
19            return serializer.Serialize(obj);
20        }

21    }

22}

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

  1using System;
  2using System.Data;
  3using System.Configuration;
  4using System.Collections;
  5using System.Linq;
  6using System.Web;
  7using System.Web.Security;
  8using System.Web.UI;
  9using System.Web.UI.WebControls;
 10using System.Web.UI.WebControls.WebParts;
 11using System.Web.UI.HtmlControls;
 12using System.Xml.Linq;
 13using BusinessObject.Projects; //dbml文件的引用
 14using System.Data.OracleClient;
 15using Database;
 16using Web.Components;
 17namespace Web.Projects.JsonDataSource
 18{
 19    public partial class ProjectBaseInfo : System.Web.UI.Page
 20    {
 21        protected string strJsonSource=string.Empty;
 22        protected void Page_Load(object sender, EventArgs e)
 23        {
 24            int start=int.Parse(Request.Form["start"]+"");      //分页需要limit,start是mysql里用的(或取当页开始的记录标识编号)
 25            int limit = int.Parse(Request.Form["limit"+ "");  //或取每页记录数
 26            string sort = Request.Form["sort"+ "";            //或取排序方向
 27            string dir = Request.Form["dir"+ "";              //或取所要排序的字段名
 28            GetJsonSouceString(start,limit,sort,dir);
 29        }

 30
 31        private void GetJsonSouceString(int start,int limit,string sort,string dir)
 32        {
 33            ProjectBaseInfoDataContext db = new ProjectBaseInfoDataContext();
 34            var query = from p in db.PROJECT_BASE_INFOs
 35                        select new { 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            排序字段和排序方向
136
137            int iCount = query.Count();   //所要记录数
138            int PageNum = start / limit;  //共有页数 
139            int PageSize = limit;
140            query = query.Skip(PageSize * PageNum).Take(PageSize);  //当前页记录
141            string JsonSource= query.ToJSON();                      //当前页记录转成JSON格式
142            strJsonSource = @"{""totalCount"":"""+iCount+"";
143            strJsonSource = strJsonSource + @""",""data"":" + JsonSource + "}";  //Grid的分页区显示所有记录数增加totalCount信息
144        }

145    }

146}

147

ProjectBaseInfo.aspx中的代码为:
<% @ Page Language = " 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页面,代码如下:

 1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2<html xmlns="http://www.w3.org/1999/xhtml">
 3<head runat="server">
 4    <title>项目一览表</title>
 5    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 6    <link rel="stylesheet" type="text/css" href="../Resources/css/ext-all.css" />
 7    <!-- GC -->
 8    <!-- LIBS -->
 9    <script type="text/javascript" src="../Adapter/ext/ext-base.js"></script>
10    <!-- ENDLIBS -->
11    <script type="text/javascript" src="../Script/ext-all.js"></script>
12
13    <script type="text/javascript" src="../Script/GridForProjectLists.js"></script>
14
15    <link rel="stylesheet" type="text/css" href="../CSS/Grid.css" />
16    <link rel="stylesheet" type="text/css" href="../CSS/Forms.css" />
17     <link rel="stylesheet" type="text/css" href="../CSS/Combos.css" />
18    <!-- Common Styles for the Projects -->
19    <style type="text/css">
20        body .x-panel
21        {
22            margin-bottom: 20px;
23        }

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

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

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

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

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

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

49        .ext-mb-save
50        {
51            background: transparent url(../Images/download.gif) no-repeat top left;
52            height: 46px;
53        }

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

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

  1/*
  2 * Ext JS Library 2.0 Beta 1
  3 * Copyright(c) 2006-2007, Ext JS, LLC.
  4 * [email protected]
  5 * 
  6 * http://extjs.com/license
  7 */

  8Ext.onReady(function(){
  9    var win;    
 10    var newwin;
 11    Ext.QuickTips.init();
 12    // create the Data Store
 13    var ds = new Ext.data.GroupingStore({
 14        // load using script tags for cross domain, if the data in on the same domain as
 15        // this page, an HttpProxy would be better
 16        proxy: new Ext.data.HttpProxy({
 17            url: '../Projects/JsonDataSource/ProjectBaseInfo.aspx'
 18        }
),
 19
 20        // create reader that reads the project records
 21        reader: new Ext.data.JsonReader({
 22            root: 'data',
 23            totalProperty: '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',
 39        remoteSort: true
 40    }
);
 41    ds.setDefaultSort('PROJECT_NAME', 'desc');
 42
 43    // pluggable renders  
 44    function renderProject(value, p, record){
 45    
 46        return String.format(
 47                '<img border=0 src="../Images/icons/application_view_list.png" id="btnView_{0}"  style="cursor:hand" alt="浏览"> &nbsp;&nbsp; <a href="ProjectDetail.aspx?ProjectNo={0}" target="_blank"><img border=0 src="../Images/icons/application_view_list.png"  style="cursor:hand" alt="编辑"></a> &nbsp;&nbsp; <a href="ProjectDetail.aspx?ProjectNo={0}" target="_blank"><img border=0 src="../Images/icons/cross.gif" style="cursor:hand" alt="删除"></a>',
 48                 record.data.PROJECT_NO);
 49    }

 50    
 51    // the column model has information about grid columns
 52    // dataIndex maps the column to the specific data field in
 53    // the data store
 54    var nm = new Ext.grid.RowNumberer();
 55    var sm = new Ext.grid.CheckboxSelectionModel();  // add checkbox column
 56    var cm = new Ext.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    //hide column
 73    cm.setHidden(4!cm.isHidden(4));   //隐藏项目简称列
 74    cm.setHidden(7!cm.isHidden(7));   //隐藏开发经理列
 75    cm.setHidden(13!cm.isHidden(13)); //隐藏备注列
 76    // by default columns are sortable
 77    cm.defaultSortable = true;
 78    var gdProjects = new Ext.grid.GridPanel({
 79        frame:true,
 80        collapsible: true,
 81        animCollapse: false,
 82        //el:'projects-grid',
 83        width :965,
 84        height:530,
 85        title:'项目一览表',
 86        iconCls: 'icon-grid',
 87        renderTo: document.body,
 88        store: ds,
 89        cm: cm,
 90        sm: sm,
 91        trackMouseOver:true,
 92        loadMask: {msg:'正在加载数据,请稍侯……'},
 93        //loadMask: true,
 94        viewConfig: {
 95            forceFit:true,
 96            enableRowBody:true,
 97            getRowClass : function(record, rowIndex, p, ds){
 98                return 'x-grid3-row-collapsed';
 99            }

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

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

你可能感兴趣的:(ExtJs)