[ASP.NET] jQuery + ListView + CheckBox 達到 Tree 的功能

摘要:[ASP.NET] jQuery + ListView + CheckBox 達到 Tree 的功能

在開發給系統管理員的功能 - 角色 - 選單 - 頁面功能 設定的頁面時,在思考著較便利的操作介面,所以就想到利用 Tree 來呈現。

但,ASP.NET 所提供的 TreeView 不是那麼的好用,網路上找了一下,後來還是覺得自已寫算了...

下圖是結果頁面 

選單名稱的呈現,可參考 暗黑大的這篇文章

節點的選擇,主要是 往上找所有父節點 及 往下找所有子節點

如上圖,在所有的 讀取權限 尚未選擇 時,點選 產品管理 的 CheckBox ,會自動將其 父節點 - XXX系統 及其 子節點 - 產品維護、產品簽核、產品報表查詢 的 CheckBox 自動選取,

因 產品維護 又有 頁面功能 的設定,所以也會一併開啟 (當 讀取權限 無勾選時,頁面功能 是不可勾選)

若將 產品維護 設為 不勾選,此時的 頁面功能 會全部清除並設定為 不可勾選狀態

若將 產品管理 設為 不勾選,此時的 子節點 - 產品維護、產品簽核、產品報表查詢 的 CheckBox  全部取消勾選,頁面功能 也如上所述

但,當所有的子節點全取消勾選時,其父節點並不會取消勾選

 

 ListView 

在 ListView 中主要是利用了以 TD 設定為 MenuID ,而該 父節點 ID 是設定在 cbCheck 的 class 屬性

方便在 jQuery 中 找到節點的 MenuID ,進而設定 所有 子節點;亦可找到節點的 ParentID,進而設定 所有父節點。

 

CheckBox cbCheck = e.Item.FindControl("cbCheck"as CheckBox;
cbCheck.Attributes.Add("onClick"string.Format("CheckBoxClick('{0}', '{1}')", item.MenuID, item.ParentID));
cbCheck.Attributes.Add("class", ((MenuTree)e.Item.DataItem).ParentID);

 

...

 

//若 無讀取權限,將 頁面功能 全不允許選取 - 設定的是 span
if (!cbCheck.Checked) pControl.Attributes.Add("disabled""disabled");

 

這邊要注意的是設定 CheckBox 的屬性時,轉成 html後如下:

透過 jQuery 抓取 CheckBox 需要留意,抓的是 span 而非 input

 

 jQuery 


	$(function () {
	})
	//主要找父節點
	function CheckBoxParentClick(ParentID) {
		if (ParentID != undefined) {
			//找父節點
			var parentCheck = $("#lvGridTable").find("#" + ParentID + " [type='checkbox']");
			var isParentCheck = $(parentCheck).attr("checked");
			if (!isParentCheck) $(parentCheck).attr("checked", "true");

			CheckBoxParentClick($(parentCheck).parent().attr("class"));
		}
	}
	//主要找子節點
	function CheckBoxClick(MenuID, ParentID) {
		var isCheck = $("#" + MenuID).find("input[type='checkbox']").attr("checked");

		//Check = true
		if (isCheck) {
			//依遞迴找父節點
			CheckBoxParentClick(ParentID);

			//頁面功能
			$("#lvGridTable").find("#Control" + MenuID + " [type='checkbox']").each(function () {
				//唯讀是指定在span,需往上一層找
				$(this).parent().removeAttr("disabled");
			});

			//找所有子節點
			$("#lvGridTable").find("." + MenuID + " [type='checkbox']").each(function () {
				$(this).attr("checked", "true");

				//checkbox 的上一層為 span,需再往上一層才找得到td - 此節點ID
				//checkbox 的 class 屬性是設定在 上一層的 span - 此節點之父節點ID
				CheckBoxClick($(this).parent().parent().attr("id"), $(this).parent().attr("class"));
			});
		}
		else {
			//頁面功能
			$("#lvGridTable").find("#Control" + MenuID + " [type='checkbox']").each(function () {
				$(this).attr("checked", "");
				//唯讀是指定在span,需往上一層找
				$(this).parent().attr("disabled", "disabled");
			});

			//找所有子節點
			$("#lvGridTable").find("." + MenuID + " [type='checkbox']").each(function () {
				$(this).attr("checked", "");

				//checkbox 的上一層為 span,需再往上一層才找得到td - 此節點ID
				//checkbox 的 class 屬性是設定在 上一層的 span - 此節點之父節點ID
				CheckBoxClick($(this).parent().parent().attr("id"), $(this).parent().attr("class"));
			});
		}
	}

 

若有更好的方式,還請不吝指教 ^^

附件:[Jero]Tree+ListView+CheckBox.zip (純HTML,非 ASP.NET)