星辰.Net技术社区论坛

首页 » .NET » 组件/控件开发 » 用ExtJs+Linq+Wcf打造简单GridView
admin - 2008-6-19 15:48:00
第一步:在vs2008中创建一个支持.net framework 3.5的网站,此处之所以强调支持.net framework 3.5是为了使用linq
第二步:将运行时需要的Extjs的资源文件拷贝到项目目录,具体可见示例项目
第三步:假设在本机sql2005中存在数据库sharelist,里面有一个数据表stocks,效果如下:

数据库文件sharelist.mdf在示例项目db文件夹中。如果需要测试,可以将其附加到自己的sql2005数据库服务器中。
在网站项目中创建一个Linq To Sql类:DataClasses.dbml,方法如下如所示:

点击添加之后,出现下面的Linq To Sql向导

在本文只使用左面面板,在服务器资源管理器中添加对数据库sharelist的连接,效果如下:

点击数据表stocks,然后拖动stocks数据表到左面面板,拖动后效果如下:

点击stocks,然后更改类名称为Stock:

更改后效果为:

好,到此我们基本完成了linq to sql类的设计,我们在解决方案管理器中打开生成的类代码文件中,其中包括类:Stock ,为了使其能够被WCF使用
,对类添加DataContractAttribute,对属性添加DataMemberAttribute,添加好之后的代码为:

linq to sql类生成的代码并添加了wcf支持
#pragma warning disable 1591

//------------------------------------------------------------------------------

// <auto-generated>

// 此代码由工具生成。

// 运行库版本:2.0.50727.1433

//

// 对此文件的更改可能会导致不正确的行为,并且如果

// 重新生成代码,这些更改将会丢失。

// </auto-generated>

//------------------------------------------------------------------------------

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Data.Linq;

using System.Data.Linq.Mapping;

using System.Linq;

using System.Linq.Expressions;

using System.Reflection;


[System.Data.Linq.Mapping.DatabaseAttribute(Name
="sharelist")]

public partial class DataClassesDataContext : System.Data.Linq.DataContext

{

   

   
private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();

   

#region Extensibility Method Definitions

partial void OnCreated();

#endregion

   

   
public DataClassesDataContext() :

           
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["sharelistConnectionString"].ConnectionString, mappingSource)

   
{

        OnCreated();

    }


   

   
public DataClassesDataContext(string connection) :

           
base(connection, mappingSource)

   
{

        OnCreated();

    }


   

   
public DataClassesDataContext(System.Data.IDbConnection connection) :

           
base(connection, mappingSource)

   
{

        OnCreated();

    }


   

   
public DataClassesDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :

           
base(connection, mappingSource)

   
{

        OnCreated();

    }


   

   
public DataClassesDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :

           
base(connection, mappingSource)

   
{

        OnCreated();

    }


   

   
public System.Data.Linq.Table<Stock> Stock

   
{

       
get

       
{

           
return this.GetTable<Stock>();

        }


    }


}




[Table(Name
="dbo.stocks")]
[DataContract]
public partial class Stock

{

   

   
private string _company;

   

   
private double _price;

   

   
private double _change;

   

   
private double _changepercent;

   

   
private System.DateTime _lastupdated;

   

   
public Stock()

   
{

    }


   

    [Column(Storage
="_company", DbType="NVarChar(50) NOT NULL", CanBeNull=false)]
    [DataMember]
   
public string company

   
{

       
get

       
{

           
return this._company;

        }


       
set

       
{

           
if ((this._company != value))

           
{

               
this._company = value;

            }


        }


    }


   

    [Column(Storage
="_price", DbType="Float NOT NULL")]
    [DataMember]
   
public double price

   
{

       
get

       
{

           
return this._price;

        }


       
set

       
{

           
if ((this._price != value))

           
{

               
this._price = value;

            }


        }


    }


   

    [Column(Storage
="_change", DbType="Float NOT NULL")]
    [DataMember]
   
public double change

   
{

       
get

       
{

           
return this._change;

        }


       
set

       
{

           
if ((this._change != value))

           
{

               
this._change = value;

            }


        }


    }


   

    [Column(Storage
="_changepercent", DbType="Float NOT NULL")]
    [DataMember]
   
public double changepercent

   
{

       
get

       
{

           
return this._changepercent;

        }


       
set

       
{

           
if ((this._changepercent != value))

           
{

               
this._changepercent = value;

            }


        }


    }


   

    [Column(Storage
="_lastupdated", DbType="DateTime NOT NULL")]
    [DataMember]
   
public System.DateTime lastupdated

   
{

       
get

       
{

           
return this._lastupdated;

        }


       
set

       
{

           
if ((this._lastupdated != value))

           
{

               
this._lastupdated = value;

            }


        }


    }


}


#pragma warning restore 1591



第四步:在网站项目中创建一个启用了Ajax的WCF服务:ArrayGridService.svc,然后将其中的类代码更改为:

using System;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Activation;

using System.ServiceModel.Web;

using System.Collections.Generic;





[ServiceContract(Namespace
= "")]

[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]

public class ArrayGridService

{

   
// 添加 [WebGet] 属性以使用 HTTP GET

    [OperationContract]

[WebInvoke(ResponseFormat
= WebMessageFormat.Json, Method = "GET", UriTemplate = "GetStocks")]

public Stock[] GetStocks()

   
{

DataClassesDataContext dbContext
= new DataClassesDataContext();

IQueryable
<Stock> res = dbContext.Stock.Select(stock => stock);

return res.ToArray<Stock>();

    }


   
// 在此处添加更多操作并使用 [OperationContract] 标记它们

}


在页面文件中,在<%@ ServiceHost中添加Factory="System.ServiceModel.Activation.WebServiceHostFactory",然后在web.config中将<enableWebScript/>替换成为<webHttp/>,注意这两个操作是必须的。到此wcf服务也准备齐备。

第五步:创建一个BasicGrid.aspx,然后在页面中添加extjs必要的链接和脚本支持,并添加页面元素,完成后的代码为:
BasicGrid.aspx页面文件
<%
@ Page Language="C#" AutoEventWireup="true" CodeFile="BasicGrid.aspx.cs" Inherits="BasicGrid"
%>



<!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>extjs+wcf+linq 打造grid</title>

<link rel="stylesheet" type="text/css" href="resources/css/ext-all.css"/>



<script type="text/javascript" src="adapter/ext/ext-base.js" charset="gb2312"></script>



<script type="text/javascript" src="ext-all.js" charset="gb2312"></script>



<script type="text/javascript" src="array-grid.js" charset="gb2312"></script>



<link rel="stylesheet" type="text/css" href="grid-examples.css"/>

<link rel="stylesheet" type="text/css" href="shared/examples.css"/>



<script type="text/javascript" src="shared/examples.js" charset="gb2312"></script>


</head>

<body>

<form id="form1" runat="server">

<div>

<h1>

extjs+wcf+linq 打造grid
</h1>

<div id="grid-example">

</div>

</div>

</form>

</body>

</html>


页面中有对<script type="text/javascript" src="array-grid.js" charset="gb2312"></script>,其中的array-grid.js便是产生grid所需要的脚本,它访问上一步中开发好的wcf服务,将服务方法GetStocks返回的json数据与extjs的grid进行绑定,具体代码如下:




/**//*

* Ext JS Library 2.1

* Copyright(c) 2006-2008, Ext JS, LLC.

* licensing@extjs.com

*

* http://extjs.com/license

*/



Ext.onReady(
function(){



// example of custom renderer function

function change(val){

if(val > 0){

return '<span style="color:green;">' + val + '</span>';

}
else if(val < 0){

return '<span style="color:red;">' + val + '</span>';

}


return val;

}




// example of custom renderer function

function pctChange(val){

if(val > 0){

return '<span style="color:green;">' + val + '%</span>';

}
else if(val < 0){

return '<span style="color:red;">' + val + '%</span>';

}


return val;

}


var proxy=new Ext.data.HttpProxy( {url:'ArrayGridService.svc/GetStocks'});



// create the data store

var store = new Ext.data.SimpleStore({

fields: [

{name: 'company'},

{name: 'price', type: 'float'},

{name: 'change', type: 'float'},

{name: 'pctChange', type: 'float'},

{name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}

]

}
);





//定义reader

var reader=new Ext.data.JsonReader(

{

}
,[

{name: 'company'},

{name: 'price'},

{name: 'change'},

{name: 'pctChange',mapping:'changepercent'},

{name: 'lastChange',mapping:'lastupdated'}

]

)

//构建Store

var store=new Ext.data.Store( {

proxy:proxy,

reader:reader

}
);

//载入

store.load();





// create the Grid

var grid = new Ext.grid.GridPanel({

store: store,

columns: [

{id:'company',header: "公司", width: 160, sortable: true, dataIndex: 'company'},

{header: "单价", width: 75, sortable: true, renderer: 'usMoney', dataIndex: 'price'},

{header: "变动", width: 75, sortable: true, renderer: change, dataIndex: 'change'},