结合Jquery的高性能ascx控件

前台代码:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="OrgTreeControl.ascx.cs"
    Inherits="Controls_OrgTreeControl" %>
<script src="../Scripts/JQuery/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="../Scripts/JQuery/jquery.json-2.2.min.js" type="text/javascript"></script>
<script src="../Scripts/JQuery/jquery.treeView.js" type="text/javascript"></script>
<link href="../../CSS/contractpage.css" rel="stylesheet" type="text/css" />
<link href="../CSS/jquery.ui.treeview.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        //传参
        var showCheckBoxs = "<% = HShowCheckBoxs.ClientID %>";
        var showNodeDepth = "<% = HShowNodeDepth.ClientID %>";
        var isAsync = "<% =HIsAsync.ClientID  %>";
        var cascadeCheck = "<% =HCascadeCheck.ClientID %>";
        var showOrgType = "<% =HShowOrgType.ClientID %>"; 

        var isCascadeCheck = true;

        var requestWhere = "";

        if ($("#" + showCheckBoxs + "").val() != "") {
            requestWhere += "showCheckBoxs=" + $("#" + showCheckBoxs + "").val() + "&";
        }
        if ($("#" + showNodeDepth + "").val() != "") {
            requestWhere += "showNodeDepth=" + $("#" + showNodeDepth + "").val() + "&";
        }
        if ($("#" + isAsync + "").val() != "") {
            requestWhere += "isAsync=" + $("#" + isAsync + "").val() + "&";
        }
        if ($("#" + showOrgType + "").val() != "") {
            requestWhere += "showOrgType=" + $("#" + showOrgType + "").val() + "&";
        }
        //组合传递的参数
        requestWhere = requestWhere.substring(0, requestWhere.length - 1);

        //是否级联选择
        if ($("#" + cascadeCheck + "").val() != "") {
            if ($("#" + cascadeCheck + "").val() == "true") {
                isCascadeCheck = true;
            }
            else {
                isCascadeCheck = false;
            }
        }

        $.ajax({
            type: "POST",
            dataType: "json",
            url: "../Controls/GetOrgDataSource.ashx?" + requestWhere + "",
            contentType: 'application/json;charset=utf-8',
            cache: false,
            success: function (data) {
                //设置默认值
                var o = { showcheck: true, cascadecheck: isCascadeCheck };
                o.data = data;

                $("#divTree").treeview(o);
            }
        });

        $("#showchecked").click(function (e) {
            var s = $("#divTree").getTSVs();
            if (s != null)
                alert(s.join(","));
            else
                alert("NULL");
        });
        $("#showcurrent").click(function (e) {
            var s = $("#divTree").getTSNs();
            var str = "";
            if (s != null) {
                for (var n = 0; n < s.length; n++) {
                    str += s[n].text;
                }
                alert(str);
            }
            else
                alert("NULL");
        });
        $("#showselected").click(function (e) {
            var s = $("#divTree").getTCT();
            if (s != null)
                alert(s.text);
            else
                alert("NULL");
        });
    });  
            
</script>
<div>
    <input type="button" id="showchecked" class="listbutton8" value="获取选择节点值" />
    <input type="button" id="showcurrent" class="listbutton8" value="获取选中节点文本" />
    <input type="button" id="showselected" class="listbutton8" value="获取选中节点文本" />
    <div style="border-bottom: #c3daf9 1px solid; border-left: #c3daf9 1px solid; width: 400px;
        height: 500px; overflow: auto; border-top: #c3daf9 1px solid; border-right: #c3daf9 1px solid;">
        <div id="divTree">
        </div>
    </div>
    <div id="controlArea">
        <input type="hidden" id="HShowCheckBoxs" value="" runat="server" />
        <input type="hidden" id="HShowNodeDepth" value="" runat="server" />
        <input type="hidden" id="HIsAsync" value="" runat="server" />
        <input type="hidden" id="HCascadeCheck" value="" runat="server" />
        <input type="hidden" id="HShowOrgType" value="" runat="server" />
    </div>
</div>


后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Controls_OrgTreeControl : System.Web.UI.UserControl
{
    public enum ShowCheckBox
    {
        /// <summary>
        /// 不显示CheckBox复选框
        /// </summary>
        None = 0,
        /// <summary>
        /// 根节点显示CheckBox复选框
        /// </summary>
        Root = 1,
        /// <summary>
        /// 父节点显示CheckBox复选框
        /// </summary>
        Parent = 2,
        /// <summary>
        /// 叶子节点显示CheckBox复选框
        /// </summary>
        Leaf = 3,
        /// <summary>
        /// 所有节点显示CheckBox复选框
        /// </summary>
        All = 4
    }

    public enum OrgType
    {
        /// <summary>
        /// 行政组织机构树
        /// </summary>
        OrganizationTree = 0,
        /// <summary>
        /// 业务组织结构树
        /// </summary>
        BusinessTree= 1,
    }

    private ShowCheckBox showCheckBoxs;
    /// <summary>
    /// 显示CheckBox
    /// </summary>
    public ShowCheckBox ShowCheckBoxs
    {
        get
        {
            return showCheckBoxs;
        }
        set
        {
            showCheckBoxs = value;
        }
    }

    private OrgType showOrgType;
    /// <summary>
    /// 树展示的组织机构类型
    /// </summary>
    public OrgType ShowOrgType
    {
        get
        {
            return showOrgType;
        }
        set
        {
            showOrgType = value;
        }
    }

    private int showNodeDepth;
    /// <summary>
    /// 树节点展示到指定的深度
    /// </summary>
    public int ShowNodeDepth
    {
        get
        {
            return showNodeDepth;
        }
        set
        {
            showNodeDepth = value;
        }
    }

    private bool isAsync;
    /// <summary>
    /// 是否异步加载数据
    /// </summary>
    public bool IsAsync
    {
        get
        {
            return isAsync;
        }
        set
        {
            isAsync = value;
        }
    }

    private bool cascadeCheck;
    /// <summary>
    /// 是否启用级联选择
    /// </summary>
    public bool CascadeCheck
    {
        get
        {
            return cascadeCheck;
        }
        set
        {
            cascadeCheck = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.CascadeCheck = false;
        this.ShowCheckBoxs = ShowCheckBox.Leaf;
        this.ShowNodeDepth = 3;

        this.HShowNodeDepth.Value = this.ShowNodeDepth.ToString();
        this.HShowCheckBoxs.Value = this.ShowCheckBoxs.ToString().ToLower();
        this.HIsAsync.Value = this.IsAsync.ToString().ToLower();
        this.HCascadeCheck.Value = this.CascadeCheck.ToString().ToLower();
    }
}


数据源读取文件采用HttpHander,代码如下:

 

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

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class GetOrgDataSource : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "application/json";
        //是否显示CheckBox
        string showCheckBoxs = context.Request.QueryString["showCheckBoxs"];
        //显示树节点的深度
        string showNodeDepth = context.Request.QueryString["showNodeDepth"];
        //是否异步加载树节点数据
        string isAsync = context.Request.QueryString["isAsync"];
        int nodeDepth = -1;//显示所有节点
        string nodeCheckBoxs = ShowCheckBox.All.ToString().ToLower(); //所有节点显示CheckBox
        if (!string.IsNullOrEmpty(showCheckBoxs))
        {
            nodeCheckBoxs = showCheckBoxs;
        }
        if (!string.IsNullOrEmpty(showNodeDepth))
        {
            nodeDepth = Convert.ToInt16(showNodeDepth);
        }
        //树结构Json字符串
        string jsonresult = GetTreeViewJson(nodeDepth, nodeCheckBoxs);
        
        context.Response.Write(jsonresult);
    
    }

    private DataTable GetTable(string commandString)
    {
        SqlConnection con = new SqlConnection("Server=.;DataBase=Exam;UID=sa;Pwd=xuwenwu_1983");
        con.Open();
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(commandString, con);
        da.Fill(ds);
        DataTable dt = ds.Tables[0];

        return dt;
    }

    public string GetTreeViewJson(int showNodeDepth, string showCheckBoxs)
    {
        string mystr = "[";
        DataTable dt = GetTable("SELECT * FROM TreeView WHERE ParentId IS NULL");
        int a = dt.Rows.Count;
        foreach (DataRow row in dt.Rows)
        {
            switch (showCheckBoxs)
            {
                case "none":    //不显示CheckBox
                    mystr += GetChildJson(row["Id"].ToString(), 0, showNodeDepth, - 2) + ",";
                    break;
                case "root":    //根节点显示CheckBox
                    mystr += GetChildJson(row["Id"].ToString(), 0,showNodeDepth, 0) + ",";
                    break;
                case "parent":  //父级节点显示CheckBox
                    mystr += GetChildJson(row["Id"].ToString(), 0, showNodeDepth, - 3) + ",";
                    break;
                case "leaf":    //叶子节点显示CheckBox
                    mystr += GetChildJson(row["Id"].ToString(), 0, showNodeDepth, - 4) + ",";
                    break;
                case "all":     //所有节点显示CheckBox
                    mystr += GetChildJson(row["Id"].ToString(), 0, showNodeDepth, - 1) + ",";
                    break;
                default:        //默认不显示CheckBox
                    mystr += GetChildJson(row["Id"].ToString(), 0, showNodeDepth, - 2) + ",";
                    break;                    
            }
        }
        mystr = mystr.Substring(0, mystr.Length - 1);
        mystr += "]";
        mystr = mystr.Replace("'", "\"");
        return mystr;
    }
    /// <summary>
    /// 递归创建子节点
    /// </summary>
    /// <param name="parentId">父节点</param>
    /// <param name="depth"></param>
    /// <param name="showCheckBoxDepth"></param>
    /// <param name="showCheckBoxs"></param>
    /// <returns></returns>
    private string GetChildJson(string parentId,int currentDepth,int showCheckBoxDepth, int showCheckBoxs)
    {
        DataTable dt = GetTable("SELECT * FROM TreeView WHERE Id = '" + parentId + "'");
        string strjson = "";
        bool haschild = IsHasChild(parentId);
        
        //CheckBox显示到指定深度
        if (currentDepth == showCheckBoxDepth)
        {
            haschild = false;
        }
        
        strjson = "{";
        strjson += "'id':'" + parentId + "',";
        strjson += "'text':'" + dt.Rows[0]["NodeName"].ToString() + "',";
        strjson += "'value':'" + dt.Rows[0]["ID"].ToString() + "',";
        //控制如何显示CheckBox
        strjson += ShowCheckBoxString(haschild, currentDepth, showCheckBoxs);
       
        strjson += " 'complete':true,";
        strjson += "'checktate':0,";
        strjson += "'hasChildren':" + haschild.ToString().ToLower() + ",";
        strjson += "'ChildNodes':";

        if (!haschild)
        {
            strjson += "null}";
        }
        else
        {
            //设置当前节点深度
            currentDepth++;
            //只显示到指定的树节点深度
            if (currentDepth <= showCheckBoxDepth)
            {
                strjson += "[";
                DataTable mydt = GetTable("SELECT * FROM TreeView WHERE ParentId='" + parentId + "'");
                foreach (DataRow row in mydt.Rows)
                {
                    strjson += GetChildJson(row["Id"].ToString(), currentDepth, showCheckBoxDepth, showCheckBoxs) + ",";
                }
                strjson = strjson.Substring(0, strjson.Length - 1);
                strjson += "]}";
            }
            else
            {
                strjson += "null}";
            }

        }
        return strjson;
    }
    /// <summary>
    /// 是否呈现CheckBox多选框
    /// </summary>
    /// <param name="haChild"></param>
    /// <param name="depth"></param>
    /// <param name="showCheckBoxs"></param>
    /// <returns></returns>
    private string ShowCheckBoxString(bool haChild, int currentDepth, int showCheckBoxs)
    {
        string strjson = "";

        switch (showCheckBoxs)
        {
            case 0://根节点显示CheckBox
                if (currentDepth == 0)
                {
                    strjson += " 'showcheck':true,";
                }
                else
                {
                    strjson += " 'showcheck':false,";
                }
                break;
            case -1://所有节点显示CheckBox
                strjson += " 'showcheck':true,";
                break;
            case -2://不显示CheckBox
                strjson += " 'showcheck':false,";
                break;
            case -3://父级节点显示CheckBox
                if (currentDepth != 0)
                {
                    if (haChild)
                    {
                        strjson += " 'showcheck':true,";
                    }
                    else
                    {
                        strjson += " 'showcheck':false,";
                    }
                }
                else
                {
                    strjson += " 'showcheck':false,";
                }
                break;
            case -4://叶子节点显示CheckBox
                if (haChild)
                {
                    strjson += " 'showcheck':false,";
                }
                else
                {
                    strjson += " 'showcheck':true,";
                }
                break;
            default:
                strjson += " 'showcheck':false,";
                break;

        }

        return strjson;
    }
    
    private bool IsHasChild(string parentId)
    {
        DataTable dt = GetTable("SELECT * FROM TreeView WHERE ParentId ='" + parentId + "'");
        if (dt.Rows.Count == 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

}


数据库结构:

USE [Exam]
GO

/****** Object:  Table [dbo].[TreeView]    Script Date: 08/25/2011 10:22:29 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[TreeView](
	[ID] [uniqueidentifier] NOT NULL,
	[NodeName] [varchar](200) NULL,
	[ParentId] [uniqueidentifier] NULL,
	[OrderNum] [int] NULL,
 CONSTRAINT [PK_TreeView] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO



整体源码:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值