本实例开发环境是:Windows XP + Sql Server 2005 + IIS6+VS 2008 Beta2(.NET Framework3.5)
实现步骤:
1.取数据源
这里是从数据库里读取数据生产JSON的方式供ExtJS Grid调用.
(1)用Scott Guthrie提供的生产JSON格式的类,
建一个类文件JSONHelper.cs,代码如下
using
System;
using System.Collections.Generic;
using System.Text;
using System.Web.Script.Serialization; namespace Web.Components
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}(2)
利用LINQ读取数据记录,为了方便ExtJS AJAX方式的调用,这里建一个ASPX页面,起名为:ProjectBaseInfo.aspx,代码如下
ProjectBaseInfo.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using BusinessObject.Projects; //dbml文件的引用
using System.Data.OracleClient;
using Database;
using Web.Components;
namespace Web.Projects.JsonDataSource
{
public partial class ProjectBaseInfo : System.Web.UI.Page
{
protected string strJsonSource=string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
int start=int.Parse(Request.Form["start"]+""); //分页需要limit,start是mysql里用的(或取当页开始的记录标识编号)
int limit = int.Parse(Request.Form["limit"] + ""); //或取每页记录数
string sort = Request.Form["sort"] + ""; //或取排序方向
string dir = Request.Form["dir"] + ""; //或取所要排序的字段名
GetJsonSouceString(start,limit,sort,dir);
}
private void GetJsonSouceString(int start,int limit,string sort,string dir)
{
ProjectBaseInfoDataContext db = new ProjectBaseInfoDataContext();
var query = from p in db.PROJECT_BASE_INFOs
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中日期格式显示的问题
排序字段和排序方向排序字段和排序方向#region 排序字段和排序方向
if (sort != "" && dir != "")
{
switch (sort)
{
case "PROJECT_NO":
if (dir == "ASC")
{
query = query.OrderBy(p => p.PROJECT_NO);
}
else
{
query = query.OrderByDescending(p => p.PROJECT_NO);
}
break;
case "PROJECT_NAME":
if (dir == "ASC")
{
query = query.OrderBy(p => p.PROJECT_NAME);
}
else
{
query = query.OrderByDescending(p => p.PROJECT_NAME);
}
break;
case "PROJECT_DEPT_NO":
if (dir == "ASC")
{
query = query.OrderBy(p => p.PROJECT_DEPT_NO);
}
else
{
query = query.OrderByDescending(p => p.PROJECT_DEPT_NO);
}
break;
case "PROJECT_MANAGER":
if (dir == "ASC")
{
query = query.OrderBy(p => p.PROJECT_MANAGER);
}
else
{
query = query.OrderByDescending(p => p.PROJECT_MANAGER);
}
break;
case "PROJECT_CURRENT_STATUS":
if (dir == "ASC")
{
query = query.OrderBy(p => p.PROJECT_CURRENT_STATUS);
}
else
{
query = query.OrderByDescending(p => p.PROJECT_CURRENT_STATUS);
}
break;
case "PROJECT_START_DATE":
if (dir == "ASC")
{
query = query.OrderBy(p => p.PROJECT_START_DATE);
}
else
{
query = query.OrderByDescending(p => p.PROJECT_START_DATE);
}
break;
case "PROJECT_FINISH_DATE":
if (dir == "ASC")
{
query = query.OrderBy(p => p.PROJECT_FINISH_DATE);
}
else
{
query = query.OrderByDescending(p => p.PROJECT_FINISH_DATE);
}
break;
case "PROJECT_REAL_START_DATE":
if (dir == "ASC")
{
query = query.OrderBy(p => p.PROJECT_REAL_START_DATE);
}
else
{
query = query.OrderByDescending(p => p.PROJECT_REAL_START_DATE);
}
break;
case "PROJECT_REAL_FINISH_DATE":
if (dir == "ASC")
{
query = query.OrderBy(p => p.PROJECT_REAL_FINISH_DATE);
}
else
{
query = query.OrderByDescending(p => p.PROJECT_REAL_FINISH_DATE);
}
break;
default:
break;
}
}
#endregion
int iCount = query.Count(); //所要记录数
int PageNum = start / limit; //共有页数
int PageSize = limit;
query = query.Skip(PageSize * PageNum).Take(PageSize); //当前页记录
string JsonSource= query.ToJSON(); //当前页记录转成JSON格式
strJsonSource = @"{""; //Grid的分页区显示所有记录数增加totalCount信息
}"totalCount"":"""+iCount+"";
strJsonSource = strJsonSource + @""",""data"":" + JsonSource + "}
}
}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页面,代码如下:
ProjectLists.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>项目一览表</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link rel="stylesheet" type="text/css" href="../Resources/css/ext-all.css" />
<!-- GC -->
<!-- LIBS -->
<script type="text/javascript" src="../Adapter/ext/ext-base.js"></script>
<!-- ENDLIBS -->
<script type="text/javascript" src="../Script/ext-all.js"></script>
<script type="text/javascript" src="../Script/GridForProjectLists.js"></script>
<link rel="stylesheet" type="text/css" href="../CSS/Grid.css" />
<link rel="stylesheet" type="text/css" href="../CSS/Forms.css" />
<link rel="stylesheet" type="text/css" href="../CSS/Combos.css" />
<!-- Common Styles for the Projects -->
<style type="text/css">
body .x-panel
{}{
margin-bottom: 20px;
}
.icon-grid
{}{
background-image: url(../Images/icons/grid.png) !important;
}
#button-grid .x-panel-body
{}{
border: 1px solid #99bbe8;
border-top: 0 none;
}
.add
{}{
background-image: url(../Images/icons/add.gif) !important;
}
.search
{}{
background-image: url(../Images/icons/plugin.gif) !important;
}
.remove
{}{
background-image: url(../Images/icons/delete.gif) !important;
}
.save
{}{
background-image: url(../Images/icons/save.gif) !important;
}
.ext-mb-save
{}{
background: transparent url(../Images/download.gif) no-repeat top left;
height: 46px;
}
</style>
</head>
<body>
</body>
</html>(注:请注意JS引用的路径)
(1)新建GridForProjectLists.js文件(这个才是核心)
代码如下:
GridForProjectLists.js
/*
* Ext JS Library 2.0 Beta 1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://extjs.com/license
*/
Ext.onReady(function(){
var win;
var newwin;
Ext.QuickTips.init();
// create the Data Store
var ds = new Ext.data.GroupingStore({
/*
* Ext JS Library 2.0 Beta 1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://extjs.com/license
*/
Ext.onReady(function(){
var win;
var newwin;
Ext.QuickTips.init();
// create the Data Store
var ds = new Ext.data.GroupingStore({
using script tags for cross domain, if the data in on the same domain as
// this page, an HttpProxy would be better
proxy: new Ext.data.HttpProxy({
url: ''../Projects/JsonDataSource/ProjectBaseInfo.aspx''
}),
// create reader that reads the project records
reader: new Ext.data.JsonReader({
root: ''data'',
totalProperty: ''totalCount''
}, [
{name:''PROJECT_NO'', type:''string''},
{name:''PROJECT_NAME'', type:''string''},
{name:''PROJECT_ALIAS'', type:''string''},
{name:''PROJECT_DEPT_NO'', type:''string''},
{name:''PROJECT_MANAGER'', type:''string''},
{name:''PROJECT_LEADER'', type:''string''},
{name:''PROJECT_CURRENT_STATUS'', type:''string''},
{name:''PROJECT_START_DATE'', type:''date''},
{name:''PROJECT_FINISH_DATE'', type:''date''},
{name:''PROJECT_REAL_START_DATE'', type:''date''},
{name:''PROJECT_REAL_FINISH_DATE'',type:''date''},
{name:''PROJECT_MEMO'', type:''string''}
]),
//groupField:''PROJECT_DEPT_NO'',
remoteSort: true
});
ds.setDefaultSort(''PROJECT_NAME'', ''desc'');
// pluggable renders
function renderProject(value, p, record){
return String.format(
''<img border=0 src=/uploadfile/201101/20/2214816906.png" id="btnView_{0}"" style="cursor:hand" alt="浏览"> <a href="ProjectDetail.aspx?ProjectNo={0}" target="_blank"><img border=0 src=/uploadfile/201101/20/2214816906.png" style="cursor:hand" alt="编辑"></a> <a href="ProjectDetail.aspx?ProjectNo={0} target="_blank"><img border=0 src=/uploadfile/201101/20/AE14816478.gif" style="cursor:hand" alt="删除"></a>'',
record.data.PROJECT_NO);
}
// the column model has information about grid columns
// dataIndex maps the column to the specific data field in
// the data store
var nm = new Ext.grid.RowNumberer();
var sm = new Ext.grid.CheckboxSelectionModel(); // add checkbox column
var cm = new Ext.grid.ColumnModel([nm,sm,
{id:''PROJECT_NO'',header:"项目编号",dataIndex: ''PROJECT_NO'', width: 40, align:''center''},
{header:"项目名称",dataIndex: ''PROJECT_NAME'', width: 100,align:''left'' },//,renderer: renderProject}
{header:"项目简称",dataIndex: ''PROJECT_ALIAS'', width: 50, align:''left''},
{header:"部门",dataIndex: ''PROJECT_DEPT_NO'', width: 50, align:''center''},
{header:"项目经理", dataIndex: ''PROJECT_MANAGER'', width: 40, align:''center''},
{header:"开发经理", dataIndex: ''PROJECT_LEADER'', width: 40, align:''center''},
{header:"当前状态",dataIndex: ''PROJECT_CURRENT_STATUS'',width: 40, align:''center''},
{header:"预计开始日期",renderer: Ext.util.Format.dateRenderer(''Y-m-d''),dataIndex: ''PROJECT_START_DATE'',width: 50, align:''center''},
{header:"预计结束日期",renderer: Ext.util.Format.dateRenderer(''Y-m-d''),dataIndex: ''PROJECT_FINISH_DATE'',width: 50, align:''center''},
{header:"实际开始日期",renderer: Ext.util.Format.dateRenderer(''Y-m-d''),dataIndex: ''PROJECT_REAL_START_DATE'',width: 50, align:''center''},
{header:"实际结束日期",renderer: Ext.util.Format.dateRenderer(''Y-m-d''),dataIndex: ''PROJECT_REAL_FINISH_DATE'',width: 50, align:''center''},
{header:"备注",dataIndex: ''PROJECT_MEMO'',width: 50, align:''left''},
{id:''PROJECT_NO'',header:"操作",dataIndex: ''PROJECT_NO'', width: 60, align:''center'',renderer:renderProject,sortable: false}
]);
//hide column
cm.setHidden(4, !cm.isHidden(4)); //隐藏项目简称列
cm.setHidden(7, !cm.isHidden(7)); //隐藏开发经理列
cm.setHidden(13, !cm.isHidden(13)); //隐藏备注列
// by default columns are sortable
cm.defaultSortable = true;
var gdProjects = new Ext.grid.GridPanel({
frame:true,
collapsible: true,
animCollapse: false,
//el:''projects-grid'',
width :965,
height:530,
title:''项目一览表'',
iconCls: ''icon-grid'',
renderTo: document.body,
store: ds,
cm: cm,
sm: sm,
trackMouseOver:true,
loadMask: {msg:''正在加载数据,请稍侯……''},
//loadMask: true,
viewConfig: {
forceFit:true,
enableRowBody:true,
getRowClass : function(record, rowIndex, p, ds){
return ''x-grid3-row-collapsed'';
}
},
view: new Ext.grid.GroupingView({
forceFit:true,
groupTextTpl: ''{text} ({[values.rs.length]}条记录)''
}),
bbar: new Ext.PagingToolbar({
pageSize: 25,
store: ds,
displayInfo: true,
displayMsg: ''当前显示 {0} - {1}条记录 /共 {2}条记录'',
emptyMsg: "无显示数据"
}),
// inline toolbars
tbar:[{
id:''btnAdd'',
text:''新增'',
tooltip:''新增'',
iconCls:''add'',
handler: showAddPanel
}, ''-'', {
text:''查询'',
tooltip:''查询'',
iconCls:''search''
}, ''-'', {
text:''批量删除'',
tooltip:''删除'',
iconCls:''remove'',
handler:showDelDialog
}]
});
}, );展示成果:
至此,本文已实现Grid的数据显示、分页、排序的功能