`
javatoyou
  • 浏览: 1017248 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

使用 ExtJS TreePanel 从 ASP.NET AJAX Web Service 获取、绑定和显示树

 
阅读更多

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]
publicclassTreeService:System.Web.Services.WebService
{
[WebMethod]
publicList<TreeNode>GetTree()
{
List
<TreeNode>list=newList<TreeNode>();

for(inti=1;i<=4;++i)
{
TreeNodeparent
=newTreeNode();
parent.id
=i;
parent.text
="节点"+i;
parent.leaf
=false;
parent.children
=newList<TreeNode>();

for(intj=1;j<=2;++j)
{
TreeNodechild
=newTreeNode();
child.id
=i*10+j;
child.text
="节点"+child.id;
child.leaf
=true;
parent.children.Add(child);
}

list.Add(parent);
}

returnlist;
}
}

请注意上面代码中的粗体部分。如果不指定此属性,ScriptManager 就不会为我们生成此 Web Service 的客户端代理,我们也就无法在客户端调用此 Web Service 中的方法。下列代码为树的节点类:

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->publicclassTreeNode
{
publicintid{get;set;}
publicstringtext{get;set;}
publicboolleaf{get;set;}
publicList<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);

functiononSuccessed(result){
//result为WebService方法GetTree的JSON形式返回值
vartree=newExt.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:
newExt.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”属性上。

程序的运行截图如下:


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics