extjs 实现右击菜单功能

1)default.aspx前台代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExtjsTreeDemo._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 type="text/css" rel="Stylesheet" href="Extjs3.2.0/resources/css/ext-all.css" />
    <script language="javascript" type="text/javascript" src="Extjs3.2.0/adapter/ext/ext-base.js"></script>
    <script language="javascript" type="text/javascript" src="Extjs3.2.0/ext-all.js"></script>
    <script language="javascript" type="text/javascript">
        Ext.onReady(initTreePanel);
        function initTreePanel() {
            //建立根
            var root = new Ext.tree.AsyncTreeNode(
            { id: '0', text: '家谱' });
            //建立树
            var tree = new Ext.tree.TreePanel({
                renderTo: 'div_tree',
                id: 'tree',
                autoScroll: true,
                border: true,
                width: 150,
                height: 500,
                useArrows: true,
                lines: true,
                animate: true,
                enableDD: true,
                containerScroll: true,
                rootVisible: true,
                root: root,
                loader: new Ext.tree.TreeLoader({ url: 'ServletHandlers/GetTrees.ashx' }),
                listeners: {
                    'contextmenu': function(node, e) {
                        node.select();
                        e.preventDefault(); //关闭右键默认菜单
                        var nodemenu = new Ext.menu.Menu({
                            items: [{
                                text: '添加节点',
                                //id: 'addNode',//添加的话右击菜单只能显示一次
                                icon: 'Extjs3.2.0/resources/images/default/tree/drop-add.gif',
                                handler: function() {
                                    Ext.Msg.prompt('请输入新节点名称:', '', function(e, text) {
                                        if (e == 'ok') {
                                            if (text == null || text == '') {
                                                Ext.Msg.alert('提示', '添加失败!节点名不能为空!');
                                            }
                                            else {
                                                //执行添加
                                                Ext.Ajax.request({
                                                    url: 'ServletHandlers/TreeHandler.ashx?type=add&parentId=' + node.id + '&text=' + text,
                                                    success: function(request) {
                                                        Ext.Msg.alert('执行结果:', '成功了!', function(e, text) {
                                                            if (e == 'ok') {
                                                                //tree.root.reload(); //数据重新加载
                                                                //tree.root.expand(true, false);
                                                                window.location.href = window.location.href;
                                                            }
                                                        });
                                                    },
                                                    failure: function() {
                                                        Ext.Msg.alert('执行结果:', '失败了!');
                                                    }
                                                })
                                            }
                                        }
                                    })
                                }
                            }, {
                                text: '删除节点',
                                //id: 'delNode',
                                icon: 'Extjs3.2.0/resources/images/default/tree/drop-no.gif',
                                handler: function() {
                                    Ext.Msg.confirm('提示:', '确认删除?', function(btn) {
                                        if (btn == 'yes') {
                                            //执行删除
                                            Ext.Ajax.request({
                                                url: 'ServletHandlers/TreeHandler.ashx?type=del&parentId=' + node.id + '&text=' + node.attributes.text,
                                                success: function(request) {
                                                    Ext.Msg.alert('执行结果:', '成功了!', function(e, text) {
                                                        if (e == 'ok') {
                                                            //tree.root.reload(); //数据重新加载
                                                            //tree.root.expand(true, false);
                                                            window.location.href = window.location.href;
                                                        }
                                                    });
                                                },
                                                failure: function() {
                                                    Ext.Msg.alert('执行结果:', '失败了!');
                                                }
                                            })
                                        }
                                    });
                                }
                            }, {
                                text: '修改节点',
                                //id: 'editNode',
                                icon: 'Extjs3.2.0/resources/images/default/tree/leaf.gif',
                                handler: function() {
                                    Ext.Msg.prompt('请输入修改后的节点名称:', '', function(e, text) {
                                        if (e == 'ok') {
                                            if (text == null || text == '') {
                                                Ext.Msg.alert('提示', '修改失败!节点名不能为空!');
                                            }
                                            else {
                                                //执行修改
                                                Ext.Ajax.request({
                                                    url: 'ServletHandlers/TreeHandler.ashx?type=edit&parentId=' + node.id + '&text=' + text,
                                                    success: function(request) {
                                                        Ext.Msg.alert('执行结果:', '成功了!', function(e, text) {
                                                            if (e == 'ok') {
                                                                //tree.root.reload(); //数据重新加载
                                                                //tree.root.expand(true, false);
                                                                window.location.href = window.location.href;
                                                            }
                                                        });
                                                    },
                                                    failure: function() {
                                                        Ext.Msg.alert('执行结果:', '失败了!');
                                                    }
                                                })
                                            }
                                        }
                                    })
                                }
}]
                            });
                            nodemenu.showAt(e.getPoint());
                        }
                    }
                });
                //单击事件
                tree.on('click', function(node, e) {
                    e.stopEvent();
                    if (!node.isExpandable()) {
                        //提交到页面处理
                        Ext.MessageBox.alert('测试', node.id);
                    }
                })
                tree.expandAll();// 加载自动显示展开节点
            }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="div_tree">
    
    </div>
    </form>
</body>
</html>

2)GetTrees.ashx 代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Text;
using System.Configuration;
namespace ExtjsTreeDemo.ServletHandlers
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class GetTrees : IHttpHandler
    {
        private string TreeDemoConnectionString = ConfigurationManager.ConnectionStrings["TreeDemoConnectionString"].ConnectionString;
        DataClassesDataContext dc = null;
        public void ProcessRequest(HttpContext context)
        {
            dc = new DataClassesDataContext(TreeDemoConnectionString);
            string str = GetParentNodeString(0);
            context.Response.ContentType = "text/plain";
            context.Response.Write(str);
        }
        /// <summary>
        /// 获取父节点
        /// </summary>
        /// <returns></returns>
        private string GetParentNodeString(int id)
        {
            int counter= 1;
            IQueryable<TreeNodes> nodes=dc.TreeNodes.Where(u=>u.parentId==id);
            StringBuilder sb = new StringBuilder();
            if (nodes != null && nodes.Count() != 0)
            {
                sb.Append("[");
                foreach (TreeNodes node in nodes)
                {
                    sb.Append("{");
                    sb.Append("id:'" + node.id + "'");
                    sb.Append(",text:'" + node.text + "'");
                    sb.Append(GetSubNodeString(node.id));
                    sb.Append("}");
                    if (counter < nodes.Count())
                    {
                        sb.Append(",");
                    }
                    counter++;
                }
                sb.Append("]");
            }
            return sb.ToString();
        }
        /// <summary>
        /// 获取子节点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private string GetSubNodeString(int id)
        {
            int counter = 1;
            IQueryable<TreeNodes> nodes = dc.TreeNodes.Where(u => u.parentId == id);
            StringBuilder sb = new StringBuilder();
            if (nodes != null & nodes.Count() != 0)
            {
                sb.Append(",children: [");
                foreach (TreeNodes node in nodes)
                {
                    sb.Append("{");
                    sb.Append("id:'" + node.id + "'");
                    sb.Append(",text:'" + node.text + "'");
                    sb.Append(GetSubNodeString(node.id));
                    sb.Append("}");
                    if (counter < nodes.Count())
                    {
                        sb.Append(",");
                    }
                    counter++;
                }
                sb.Append("]");
            }
            else
            {
                sb.Append(",leaf: true");
                //sb.Append(",href:'http://www.baidu.com?id="+id+"'");
                //sb.Append(",hrefTarget:'_blank'");
            }
            return sb.ToString();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

3)TreeHandler.ashx代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Data.Linq;
namespace ExtjsTreeDemo.ServletHandlers
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class TreeHandler : IHttpHandler
    {
        private string TreeDemoConnectionString = ConfigurationManager.ConnectionStrings["TreeDemoConnectionString"].ConnectionString;
        DataClassesDataContext dc = null;
        public void ProcessRequest(HttpContext context)
        {
            dc = new DataClassesDataContext(TreeDemoConnectionString);
            string type = "";
            int parentId = 0;
            string text = "";
            if (context.Request.QueryString["type"] != null)
            {
                type = context.Request.QueryString["type"].ToString();
            }
            if (context.Request.QueryString["parentId"] != null)
            {
                string strId = context.Request.QueryString["parentId"].ToString();
                parentId = Convert.ToInt32(strId);
            }
            if (context.Request.QueryString["text"] != null)
            {
                text = context.Request.QueryString["text"].ToString();
            }
            if (type == "add")
            {
                TreeNodes node = new TreeNodes();
                node.text = text;
                node.parentId = parentId;
                bool flag = AddNode(node);
            }
            else if (type == "del")
            {
                TreeNodes node = GetNode(parentId);
                if (node != null)
                {
                    bool flag = DelNode(node);
                    DelNodesEvent(parentId);
                }
            }
            else
            {
                TreeNodes node = GetNode(parentId);
                bool flag = EditNode(node, text);
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write("response");
            
        }
        /// <summary>
        /// 递归删除所有的字节点
        /// </summary>
        /// <param name="parentId"></param>
        private void DelNodesEvent(int parentId)
        {
            IQueryable<TreeNodes> nodes = GetNodes(parentId);
            if (nodes != null && nodes.Count() != 0)
            {
                foreach (TreeNodes node in nodes)
                {
                    DelNodesEvent(node.id);
                }
                DelNodes(nodes);
            }
        }
        /// <summary>
        /// 根据id获取节点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private TreeNodes GetNode(int id)
        {
            TreeNodes node = null;
            node=dc.TreeNodes.SingleOrDefault(u => u.id == id);
            return node;
        }
        /// <summary>
        /// 根据parentId删除多个节点
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private IQueryable<TreeNodes> GetNodes(int parentId)
        {
            IQueryable<TreeNodes> nodes = null;
            nodes = dc.TreeNodes.Where(u => u.parentId == parentId);
            return nodes;
        }
        /// <summary>
        /// 添加节点
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private bool AddNode(TreeNodes node)
        {
            bool flag = false;
            try
            {
                dc.TreeNodes.InsertOnSubmit(node);
                dc.SubmitChanges();
                flag = true;
            }
            catch (Exception ex)
            {
                flag = false;
            }
            return flag;
        }
        /// <summary>
        /// 删除节点
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private bool DelNode(TreeNodes node)
        {
            bool flag = false;
            try
            {
                dc.TreeNodes.DeleteOnSubmit(node);
                dc.SubmitChanges();
            }
            catch (Exception ex)
            {
                flag = false;
            }
            return flag;
        }
        /// <summary>
        /// 删除多个节点
        /// </summary>
        /// <param name="nodes"></param>
        /// <returns></returns>
        private bool DelNodes(IQueryable<TreeNodes> nodes)
        {
            bool flag = false;
            try
            {
                dc.TreeNodes.DeleteAllOnSubmit(nodes);
                dc.SubmitChanges();
            }
            catch (Exception ex)
            {
                flag = false;
            }
            return flag;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="node"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        private bool EditNode(TreeNodes node, string text)
        {
            bool flag = false;
            node.text = text;
            try
            {
                dc.SubmitChanges();
                flag = true;
            }
            catch (Exception ex)
            {
                flag = false;
            }
            return flag;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值