制作树形菜单的原理是:首先连接数据库,将数据按照树的结构形式返回,在客户端遍历数据时,将每条记录生成一个treepanel,然后在每个treepanel都包含在一个Panel组件里面,最后在将每个Panel组件都添加到一个上级Panel组件里面,最后在将这个上级Panel添加到Viewport里面.这里用到三个Ext组件,分别是:Viewport ; Panel ; TreePanel.
这里先简单介绍下这三个组件:
1,Panel 是Ext控件的基础,它可以用来创建非常漂亮的界面,是一个功能强大,使用却非常简单的容器组件.像面板的展开与关闭功能就非常不错.
2,TreePanel,看名字就知道树的组件就是继承自Panel 组件,在以前如果要在客户端实现一个树是很麻烦的,要处理样式,写很多的脚本,并且还要考虑Ajax.但是现在就方便多了,你要做的就是设置几个属性而已,唯一要注意的是,在显示一棵树时,必须为它指定一个根节点,不过,这更简单.
3,Viewport 代表整个浏览器的显示区域,并会随着显示区域的大小而自动改变,一个页面有且只能够有一个Viewport .
下面在将代码复制出来之前,先看看效果图,因为效果图很精美,能够增加你的胃口:
按顺序将效果图依次展开,包括面板关闭,面板展开,树菜单展开,树菜单依次展开等
1,将整个页面完整复制过来,你就会发现,Ext仅仅几行代码就能够实现非常强大的应用
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="Example_TreeAutoLoad_Default" %>
<!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>
<link rel="Stylesheet" type="text/css" href="ExtJS/resources/css/ext-all.css" />
<link rel="Stylesheet" type="text/css" href="ExtJS/resources/css/xtheme-purple.css" />
<link rel="Stylesheet" type="text/css" />
<script type="text/javascript" src="ExtJS/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="ExtJS/ext-all.js"></script>
<script type="text/javascript" src="ExtJS/ext-lang-zh_CN.js"></script>
<style type="text/css">
.panel_icon { background-image:url(images/first.gif)}
.center_icon { background-image:url(images/center.png)}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<script type="text/javascript">
//以下是关键代码 因为是提高篇,所以假想你已经对Ext很熟悉了,
//即使不熟悉也没有关系,我会继续把未完的基础篇尽快完成
function makeTreeMenu()
{
var panel_west = new Ext.Panel
({
id:'panWestMenu',
region:'center',
title:'销售管理系统',
split:true,
width: 200,
collapsible: true,
margins:'0 0 0 0',
layout:'accordion',
layoutConfig:{animate:true}
});
var viewport = new Ext.Viewport
({
id:'vpMain',
layout:'border',
items:
[
panel_west
]
});
var CreateMenuPanel = function(title,TypeID)
{
return new Ext.Panel
({
title:title,layout:'fit',border: false,frame:true,
items:
[{
xtype:'treepanel',singleExpand:true,animate:true,autoScroll:true,containerScroll: true,
border: false,
width:200,height:370,enableDD:false,dropConfig: {appendOnly:true},
loader: new Ext.tree.TreeLoader({dataUrl:"json.aspx?Param=1"}),
root:new Ext.tree.AsyncTreeNode
({
id:TypeID,
text: title,
draggable:false,
expanded:true
})
}]
});
};
//加载左面的数据
var loadPanelWest = function()
{
Ext.Ajax.request
({
url: 'json.aspx?Param=0',
success: function(response, options)
{
try
{
var panWestMenu = Ext.getCmp("panWestMenu");
if(panWestMenu)
{
var children = panWestMenu.findByType('panel');
if(children)
{
for(var i=0, len = children.length; i<len; i++)
{
panWestMenu.remove(children[i],true);
}
}
}
var menusArray = Ext.util.JSON.decode(response.responseText);
for(var i=0; i<menusArray.length; i++)
{
var mp = CreateMenuPanel(menusArray[i].TypeTitle,menusArray[i].TypeID);
panWestMenu.add(mp);
}
panWestMenu.doLayout();
}
catch(e)
{
}
}
});
};
loadPanelWest();
}
</script>
<script type="text/javascript">
function ready()
{
makeTreeMenu();
}
Ext.onReady(ready);
</script>
</div>
</form>
</body>
</html>
2,显示完整后台cs代码json.aspx.cs
using Ext;
using System.Collections.Generic;
using Newtonsoft.Json;
public partial class Example_TreeAutoLoad_json : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string param = Request["Param"];
if (param == "0")
{
List<Ext.TreeNode> nodes = new List<Ext.TreeNode>();
string res = "";
try
{
DataSet ds = DataBusiness.GetMoreRow(Convert.ToString(param));
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow row = ds.Tables[0].Rows[i] as DataRow;
Ext.TreeNode node = new Ext.TreeNode();
node.id = Convert.ToString(row["ID"]);
node.parentNodeId = param;
node.IsRoot = false;
node.leaf = false;
node.draggable = true;
node.text = Convert.ToString(row["TypeCName"]);
node.TypeID = Convert.ToString(row["ID"]);
node.PID = Convert.ToString(param);
node.TypeTitle = Convert.ToString(row["TypeCName"]);
node.TypeEName = Convert.ToString(row["TypeCName"]);
node.DelFlag = Convert.ToBoolean(row["DelFlag"]);
nodes.Add(node);
}
}
res = JavaScriptConvert.SerializeObject(nodes);
}
catch (Exception ee)
{
string error = ee.Message;
}
Response.Write(res);
}
else
{
if (Request["node"] == null || Convert.ToString(Request["node"]) == "")
return;
List<Ext.TreeNode> nodes = new List<Ext.TreeNode>();
string res2 = "";
try
{
DataSet ds = DataBusiness.GetMoreRow(Convert.ToString(Request["node"]));
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow row = ds.Tables[0].Rows[i] as DataRow;
Ext.TreeNode node = new Ext.TreeNode();
node.id = Convert.ToString(row["ID"]);
node.parentNodeId = Convert.ToString(Request["node"]);
node.IsRoot = false;
node.leaf = (DataBusiness.HasChildNode(node.id));
node.draggable = true;
node.text = Convert.ToString(row["TypeCName"]);
node.TypeID = Convert.ToString(row["ID"]);
node.PID = Convert.ToString(Request["node"]);
node.TypeTitle = Convert.ToString(row["TypeCName"]);
node.TypeEName = Convert.ToString(row["TypeCName"]);
node.DelFlag = Convert.ToBoolean(row["DelFlag"]);
nodes.Add(node);
}
}
res2 = JavaScriptConvert.SerializeObject(nodes);
}
catch (Exception ee)
{
string error = ee.Message;
}
Response.Write(res2);
}
}
}
3,将涉及的实体类代码完整复制
namespace Ext
{
// 摘要:
// Class that represents an ExtJs TreeNode
[Serializable]
public class TreeNode
{
// 摘要:
// Initializes a new instance of the TreeNode class.
public TreeNode()
{
}
// 摘要:
// Css class to render a different icon to a node
private string _cls;
public string cls
{
get { return _cls; }
set { _cls = value; }
}
//
// 摘要:
// If the node is draggabe
private bool _draggable;
public bool draggable
{
get { return _draggable; }
set { _draggable = value; }
}
//
// 摘要:
// URL of the link used for the node (defaults to #)
private string _href;
public string href
{
get { return _href; }
set { _href = value; }
}
//
// 摘要:
// target frame for the link
private string _hrefTarget;
public string hrefTarget
{
get { return _hrefTarget; }
set { _hrefTarget = value; }
}
//
// 摘要:
// The path to an icon for the node. The preferred way to do this is to use
// the cls or iconCls attributes and add the icon via a CSS background image.
private string _icon;
public string icon
{
get { return _icon; }
set { _icon = value; }
}
//
// 摘要:
// Node id
private string _id;
public string id
{
get { return _id; }
set { _id = value; }
}
//
// 摘要:
// If a node is checked (only if tree is checkbox tree)
private bool _IsChecked;
public bool IsChecked
{
get { return _IsChecked; }
set { _IsChecked = value; }
}
//
// 摘要:
// If this is the root node
private bool _IsRoot;
public bool IsRoot
{
get { return _IsRoot; }
set { _IsRoot = value; }
}
//
// 摘要:
// If it has children then leaf=false
private bool _leaf;
public bool leaf
{
get { return _leaf; }
set { _leaf = value; }
}
//
// 摘要:
// Gets or sets the type of the node.
private string _NodeType;
public string NodeType
{
get { return _NodeType; }
set { _NodeType = value; }
}
//
// 摘要:
// Id of the parent node
private string _parentNodeId;
public string parentNodeId
{
get { return _parentNodeId; }
set { _parentNodeId = value; }
}
//
// 摘要:
// Text of the node
private string _text;
public string text
{
get { return _text; }
set { _text = value; }
}
private string typeID;
public string TypeID
{
get { return typeID; }
set { typeID = value; }
}
private string pID;
public string PID
{
get { return pID; }
set { pID = value; }
}
private string typeEName;
public string TypeEName
{
get { return typeEName; }
set { typeEName = value; }
}
private string description;
public string Description
{
get { return description; }
set { description = value; }
}
private string typeTitle;
public string TypeTitle
{
get { return typeTitle; }
set { typeTitle = value; }
}
private DateTime addDate;
public DateTime AddDate
{
get { return addDate; }
set { addDate = value; }
}
private bool delFlag;
public bool DelFlag
{
get { return delFlag; }
set { delFlag = value; }
}
}
}
4,因业务逻辑仅仅涉及2个查询较为简单,这里不再列出,仅将数据表的生成脚本完整显示
CREATE TABLE [dbo].[TypeTable](
[ID] [int] IDENTITY(1,1) NOT NULL,
[PID] [int] NULL,
[TypeEName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[TypeCName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[DelFlag] [bit] NULL CONSTRAINT [DF_TypeTable_DelFlag] DEFAULT ((0)),
[AddDate] [datetime] NULL CONSTRAINT [DF_TypeTable_AddDate] DEFAULT (getdate()),
CONSTRAINT [PK_TypeTable] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]