Easy UI Tree 动态加载tree、异步加载

刚接触Easy UI,很多东西还是粗放式的,望理解。

后台采用的是ahsx 

代码如下:

 Handler.ashx


<%@ WebHandler Language= " C# " Class= " Handler " %>

using System;
using System.Web;

public  class Handler : IHttpHandler {
    
     public  void ProcessRequest (HttpContext context) {
        context.Response.ContentType =  " text/plain ";
         string method = context.Request[ " action "];
         switch (method)
        {
             case  " GetModule ":
                {
                     string a = context.Request.Params[ " id "]; // 参数为id
                    TreeViewCommon treeViewCommon =  new TreeViewCommon();
                    
                    context.Response.Write(treeViewCommon.GetModule());
                     break;
                }
             default:
                 break;
        }
    }
 
     public  bool IsReusable {
         get {
             return  false;
        }
    }
}

 

 Cs文件如下:TreeViewCommon.cs

 

  public    string  GetModule() 

    {
        string sql = "SELECT m.ID, m.Name, m.ParentID, m.Url, m.Ico FROM Module m ORDER BY m.Level, m.[Index]";
        DataTable dt = GetTable(sql);
        return TableToEasyUITreeJson(dt, "ParentID""0""ID""Name").Substring(12);
    }
    /// 


    
/// 递归将DataTable转化为适合jquery easy ui 控件tree ,combotree 的 json
    
/// 该方法最后还要 将结果稍微处理下,将最前面的,"children" 字符去掉.
    
/// 

    
/// 要转化的表
    
/// 表中的父节点字段
    
/// 表中顶层节点的值,没有 可以输入为0
    
/// 关键字字段名称
    
/// 要显示的文本 对应的字段
    
/// 
    public static string TableToEasyUITreeJson(DataTable dt, string pField, string pValue, string kField, string TextField)
    {
        StringBuilder sb = new StringBuilder();
        string filter = String.Format(" {0}='{1}' ", pField, pValue);//获取顶级目录.
        DataRow[] drs = dt.Select(filter);
        if (drs.Length < 1)
            return "";
        sb.Append(",\"children\":[");
        foreach (DataRow dr in drs)
        {
            string pcv = dr[kField].ToString();
            sb.Append("{");
            sb.AppendFormat("\"id\":\"{0}\",", dr[kField].ToString());
            sb.AppendFormat("\"text\":\"{0}\"", dr[TextField].ToString());
            sb.Append(TableToEasyUITreeJson(dt, pField, pcv, kField, TextField).TrimEnd(','));
            sb.Append("},");
        }
        if (sb.ToString().EndsWith(","))
        {
            sb.Remove(sb.Length - 11);
        }
        sb.Append("]");
        return sb.ToString();

    }

 

 aspx文件如下:

导入jquery- 1.7. 2.min.js、jquery.easyui.min.js、和自己的js(我在这里叫tree.js)文件
加入:
" mytree "  class = " easyui-tree " >  

 tree.js文件如下

  

var  dd =  ' [{"id":"0001","text":"1","children":[{"id":"00010001","text":"4","children":[{"id":"000100010001","text":"7","children":[{"id":"0001000100010001","text":"9","children":[{"id":"00010001000100010001","text":"10","children":[{"id":"000100010001000100010001","text":"11","children":[{"id":"0001000100010001000100010001","text":"12"}]}]}]}]},{"id":"000100010002","text":"8"}]},{"id":"00010002","text":"5"},{"id":"00010003","text":"6"}]},{"id":"0002","text":"2"},{"id":"0003","text":"3"}] ' ;
    $(function () {
        $( ' #mytree ').tree({
             //                 data: eval(dd)
            
//                 onClick: function (node) {
            
//                     $('#mytree').tree('beginEdit', node.target);
            
//                 }

            url:  ' Handler.ashx?action=GetModule '
        });
    });

 

 

第二种方式,运用扩展实现一步加载

 扩展内容如下:

(function () {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//地址:http://git.oschina.net/gson/jeasyuicn-ext/tree/master/ext.easyui/ext.tree/properties.loader
//用法:
//*带参数初始化

//$("#tree").tree({
//    url:'tree.do'
//    queryParams:{pid:1}
//});

//*参数变更

//$("#tree").tree("setQueryParams",{pid:1});


//重写tree的loader
$.extend($.fn.tree.defaults, {
    loader: function (param, success, error) {
        var opts = $(this).tree("options");
        if (!opts.url) {
            return false;
        }
        if (opts.queryParams) {
            param = $.extend({}, opts.queryParams, param);
        }
        $.ajax({
            type: opts.method,
            url: opts.url,
            data: JSON2.stringify(param),
            dataType: "text",
            contentType: "application/json; charset=utf-8", //application/json
            success: function (data) {
                success(JSON2.parse(data));
            },
            error: function () {
                error.apply(this, arguments);
            }
        });
    },
    queryParams: {}
});
//设置参数
$.extend($.fn.tree.methods, {
    setQueryParams: function (jq, params) {
        return jq.each(function () {
            $(this).tree("options").queryParams = params;
        });
    }
});
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
})(jQuery);

调用方法如下:

    //运用扩展实现Tree的异步加载
    //$("#menu").tree("setQueryParams", { "parentID": 0 });
    $("#menu").tree({
        url: 'http://ehlccs.cn/ControlServices.svc/GetAsynEasyTree',
        queryParams: { "parentID": 0 },
        loadFilter: function (data) { //loadFilter 用于webServices、服务等【因为前面多个d】
            if (data.d) {
                return eval('(' + data.d + ')');
            } else {
                return eval('(' + data + ')');
            }
        },
        onBeforeExpand: function (node) {
            $("#menu").tree("setQueryParams", { "parentID": node.id });
            $('#menu').tree('options').url = "http://ehlccs.cn/ControlServices.svc/GetAsynEasyTree";
        }
    });
    

数据层方法:

/// 
        /// 获取菜单信息,异步加载Tree
        /// 
        /// ParentID
        /// 
        public DataTable GetAsynTree(long parentID)
        {
            var dataManager = new DataManager("TreeDB", "GetAsynTree");
            IOHelper.WriteLine(@"E:\a.txt", parentID.ToString());
            dataManager.SetParameters("@ParentID", Convert.ToInt64(parentID));
            DataTable dt = new DataTable();
            dataManager.ExecuteDataTable(dt);
            return dt;
        }

   #region DataTable转EasyUiTree的Json格式
        /// 
        /// DataTable转EasyUiTree的Json格式 【内部方法,不做过多验证】
        /// 
        /// 要转化的表
        /// 父节点对应字段
        /// 父节点的值,默认为"0"
        /// ID对应的字段
        /// Name对应的字段
        /// 是否是父节点对应的字段
        /// 是否选择父节点,有单选框、复选框的时候用;true:checkbox radio 可以选择父节点/子节点;false:radio 只能选择叶子节点
        /// url对应字段,可以为null  ""
        /// 图片对应字段,可以为null  ""
        ///  
        private static string CartDataTableToTreeJson1(DataTable dt, string pField, string pValue, string idField, string nameField, string isParentField, bool? isChooseParentNode, string url, string icon)
        {

            StringBuilder sb = new StringBuilder();
            string filter = String.Format(" {0}={1} ", pField, pValue); //获取顶级目录.


            DataRow[] drs = dt.Select(filter);
            if (drs.Length < 1)
                return "";
            sb.Append(",\"children\":[");
            foreach (DataRow dr in drs)
            {
                IOHelper.WriteLine(@"E:\a.txt", dr[idField].ToString());
                string pcv = dr[idField].ToString();
                sb.Append("{");
                string strIsParent = dr[isParentField].ToString().Trim().ToLower();

                //string strIsParent = "false";
                if (strIsParent.Equals("true"))
                {
                    if (!string.IsNullOrWhiteSpace(url))
                    {
                        sb.AppendFormat("\"id\":\"{0}\",", dr[idField].ToString().Trim() + "," + dr[url].ToString().Trim());
                    }
                    else
                    {
                        sb.AppendFormat("\"id\":\"{0}\",", dr[idField].ToString().Trim());
                    }
                }
                else
                {
                    sb.AppendFormat("\"id\":\"{0}\",", dr[idField].ToString().Trim());
                }
                sb.AppendFormat("\"text\":\"{0}\",", dr[nameField].ToString().Trim());

                if (!string.IsNullOrWhiteSpace(icon))
                    sb.AppendFormat("\"iconCls\":\"{0}\",", dr[icon].ToString().Trim());

                //if (strIsParent.Equals("false"))
                //    if (!string.IsNullOrWhiteSpace(url))
                //    {
                //        sb.Append("\"attributes\":{");
                //        sb.AppendFormat("\"url\":\"{0}\",", dr[url].ToString().Trim());
                //        sb.Append("},");
                //    }

                //if (isChooseParentNode.Equals(false))
                //    if (strIsParent.Equals("true"))
                //        sb.AppendFormat("\"nocheck\":\"{0}\",", true);
                sb.AppendFormat("\"state\":\"{0}\"", strIsParent.Equals("true") ? "open" : "closed");

                sb.Append(CartDataTableToTreeJson1(dt, pField, pcv, idField, nameField, isParentField, isChooseParentNode, url, icon).TrimEnd(','));
                sb.Append("},");
            }
            if (sb.ToString().EndsWith(","))
            {
                sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]");
            return sb.ToString();
        }
        #endregion




SQL语句:

"GetAsynTree" CommandType="Text"  CommandDescrip="获取菜单信息,异步加载Tree">
    
      [CDATA[
       --DECLARE @ParentID BIGINT
        --SET @ParentID = 0

        DECLARE @IsLeafNode BIT
        SET @IsLeafNode = 0

        SELECT m.ID, m.Name, m.[Url], m.Icon, m.[Level], m.[Index], m.IsEnabled,m.ParentID, m.SecondAncestorID,isnull(n.ChildNodesNumber,0) ChildNodesNumber,isnull(n.IsLeafNode,1) IsLeafNode FROM Module m
        LEFT  JOIN 
        (
        SELECT ParentID ID,COUNT(ParentID) ChildNodesNumber, @IsLeafNode IsLeafNode FROM Module
        GROUP BY ParentID
        ) n
        ON m.ID=n.ID
        WHERE  ParentID=@ParentID
      ]]>
    
    
      
      "@ParentID" DbType="Int64"/>
    

 

转载于:https://www.cnblogs.com/puke/archive/2012/08/08/2627820.html

你可能感兴趣的:(Easy UI Tree 动态加载tree、异步加载)