ExtJs与WCF交互:生成树

上文做了下Ajax与WCF进行json交互的简单介绍,本文阐述一个具体的实际应用:ExtJs与WCF交互,生成树.也很简单.先看看最终的效果吧:

ExtJs与WCF交互:生成树

第一步: 创建一个.net framework 3.5的网站项目ExtJsTreeWcf

第二步: 在网站项目中创建一个启用了Ajax的WCF服务WcfTreeService.svc,创建好之后,对该服务做如下的更改:

1)在WcfTreeService.svc中增加Factory="System.ServiceModel.Activation.WebServiceHostFactory",打开WcfTreeService.Svchtml编辑器的方法如下:

ExtJs与WCF交互:生成树

ExtJs与WCF交互:生成树

添加Factory之后的html为

2)去除web.config中的<enableWebScript/>

ExtJs与WCF交互:生成树

第三步:在WcfTreeService.svc修改代码为:

[DataContract]

publicclass
treenode

{

[DataMember]

publicstring
id;

[DataMember]

publicstring
text;

[DataMember]

publicList<treenode>children=newList<treenode>
();

[DataMember]

publicstring
cls;

[DataMember]

publicbool
leaf;

}


[ServiceContract(Namespace
=""
)]

[AspNetCompatibilityRequirements(RequirementsMode
=
AspNetCompatibilityRequirementsMode.Allowed)]

publicclass
WcfTreeService

{

//添加[WebGet]属性以使用HTTPGET


[OperationContract]

[WebInvoke(ResponseFormat
=WebMessageFormat.Json)]

public
treenode[]GetTree()

{

//在此处添加操作实现


treenodet
=newtreenode();

t.id
="noe1"
;

t.text
="节点1"
;

t.cls
="folder"
;

treenodet0
=new
treenode();

t0.id
="noe1_0"
;

t0.text
="节点1_0"
;

t0.cls
="folder"
;

t0.leaf
=true
;

t.children.Add(t0);

treenodet1
=new
treenode();

t1.cls
="folder"
;

t1.id
="000"
;

t1.text
="节点1"
;

treenodet2
=new
treenode();

t2.id
="noe1_1"
;

t2.text
="节点1_1"
;

t2.cls
="folder"
;

t2.leaf
=true
;

t1.children.Add(t2);

List
<treenode>nodes=newList<treenode>
();

nodes.Add(t);

nodes.Add(t1);

return
nodes.ToArray();

}




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


}


}

其中treenode是数据契约,而WcfTreeService是服务契约,服务操作GetTree返回Json编码格式数据

第四步:拷贝extjs的脚本资源拷贝到项目中的js目录,然后在default.aspx中添加对extjs脚本的引用:

<linkrel="stylesheet"type="text/css"href="js/ext2.1/resources/css/ext-all.css">

<scripttype="text/javascript"src="js/ext2.1/adapter/ext/ext-base.js"></script>


<scripttype="text/javascript"src="js/ext2.1/ext-all.js"></script>


第五步:在default.aspx增加如下的页面元素:

<h2>ExtJs与WCF交互-树</h2>


<divid="tree-div">


</div>


在<head></head>中添加如下脚本:

<scripttype="text/javascript">

Ext.onReady(
function()
{

varTree=
Ext.tree;

vartree=newTree.TreePanel(
{

rootVisible:
false
,

el:
'tree-div',//目标div容器


width:
175,

height:
200
,

autoScroll:
true
,

animate:
true
,

enableDD:
true
,

loader:
newTree.TreeLoader(
{

dataUrl:
'WcfTreeService.svc/GetTree'


}
)

}
);

varroot=newTree.AsyncTreeNode(
{

text:
'根结点'
,

draggable:
false
,

id:
'-100'


}
);

tree.setRootNode(root);

tree.render();

root.expand();

}
);

</script>


浏览页面default.aspx便出现文章开头的页面效果

利用httpwacth察看WcfTreeService.svc/GetTree的输出如下:

[{"children": [{"children":[],"cls":"folder","id":"noe1_0","leaf":true,"text":"节点 1_0"}],"cls":"folder","id":"noe1","leaf":false,"text":"节点1"}, {"children":[{"children":[],"cls":"folder","id":"noe1_1","leaf":true,"text": "节点1_1"}],"cls":"folder","id":"000","leaf":false,"text":"节点1"}]

程序示例项目: /Files/jillzhang/ExtJsTreeWcf.rar

你可能感兴趣的:(ExtJs)