1.Web Service
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->
[WebService(Namespace
=
"
http://tempuri.org/
"
)]
[WebServiceBinding(ConformsTo
=
WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(
false
)]
[System.Web.Script.Services.ScriptService]
public
class
TreeService:System.Web.Services.WebService
{
[WebMethod]
public
List
<
TreeNode
>
GetTree()
{
List
<
TreeNode
>
list
=
new
List
<
TreeNode
>
();
for
(
int
i
=
1
;i
<=
4
;
++
i)
{
TreeNodeparent
=
new
TreeNode();
parent.id
=
i;
parent.text
=
"
节点
"
+
i;
parent.leaf
=
false
;
parent.children
=
new
List
<
TreeNode
>
();
for
(
int
j
=
1
;j
<=
2
;
++
j)
{
TreeNodechild
=
new
TreeNode();
child.id
=
i
*
10
+
j;
child.text
=
"
节点
"
+
child.id;
child.leaf
=
true
;
parent.children.Add(child);
}
list.Add(parent);
}
return
list;
}
}
请注意上面代码中的粗体部分。如果不指定此属性,ScriptManager 就不会为我们生成此 Web Service 的客户端代理,我们也就无法在客户端调用此 Web Service 中的方法。下列代码为树的节点类:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->
public
class
TreeNode
{
public
int
id{
get
;
set
;}
public
string
text{
get
;
set
;}
public
bool
leaf{
get
;
set
;}
public
List
<
TreeNode
>
children{
get
;
set
;}
}
需要注意的是,节点类的各属性名称必须与上面代码中完全相同,且必须全部是小写字母(数据类型可以不一样,如:您可以将 id 属性改为 String 型),否则 ExtJS 的 TreePanel 将无法识别。
2.客户端
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->
<
formid
=
"
form1
"
runat
=
"
server
"
>
<
asp:ScriptManagerID
=
"
ScriptManager1
"
runat
=
"
server
"
>
<
Services
>
<
asp:ServiceReferencePath
=
"
Services/TreeService.asmx
"
/
>
<
/
Services>
<
/
asp:ScriptManager>
<
divid
=
"
tree
"
><
/
div>
<
scripttype
=
"
text/javascript
"
>
Ext.onReady(
function
(){
//
调用WebService
TreeService.GetTree(onSuccessed);
function
onSuccessed(result){
//
result为WebService方法GetTree的JSON形式返回值
var
tree
=
new
Ext.tree.TreePanel({
el:
"
tree
"
,
animate:
true
,
title:
"
ExtJS树
"
,
collapsible:
true
,
enableDD:
true
,
enableDrag:
true
,
rootVisible:
true
,
autoScroll:
true
,
autoHeight:
true
,
width:
150
,
lines:
true
,
root:
new
Ext.tree.AsyncTreeNode({
id:
"
root
"
,
text:
"
根节点
"
,
expanded:
true
,
leaf:
false
,
children:result
//
将从WebService取到的所有节点绑定到根节点下。
})
});
tree.render();
}
});
<
/
script>
<
/
form>
在客户端,我们首先调用 Web Service 的 GetTree 方法获取节点列表,然后创建 TreePanel 控件,并生成“根节点”。由于使用 Web Service 客户端代理与 Web Service 交互时发送和接收的数据均为 JSON 形式(可参考《ASP.NET AJAX 中在客户端用 WebRequest 调用 Web Service》一文),因此,我们从 GetTree 方法取得的数据必然也是 JSON 形式。于是我们就可以将返回的数据直接送给 TreePanel。在上面代码中,我们将返回的节点数据绑定到根节点的“children”属性上。
程序的运行截图如下: