浅谈ASP.NET中的TreeView


  本文标签:TreeView ASP.NET

  ASP.NET 2.0 的 TreeView 控件功能虽说强大,但其客户端控制很逊色,本文将讲解 TreeView 的客户端实现原理,并实现两个个性化操作:

  (1) 节点的全部打开和关闭;
Client Side Expand/Collapse All Nodes For ASP.NET 2.0 TreeView.

  (2) 只打开一个节点(关闭其他兄弟节点)  。
Just one expanded node in ASP.NET 2.0 TreeView (When a client expand one node all other will collaps)
用记事本打开页面源代码,可以找到一下两个脚本引用:

  1. <script src="/WebUI/WebResource.axd?d=RAQeBcDUNuP9iuS8q3tNEw2&
    t=633300220640000000"
     type="text/javascript">script> 
  2. <script src="/WebUI/WebResource.axd?d=JuTdJhq3NM8Jq_RhssAkEg2&
    t=633300220640000000"
     type="text/javascript">script> 

  
将"/WebUI/WebResource.axd?d=RAQeBcDUNuP9iuS8q3tNEw2& amp;t=633300220640000000"拷到地址栏尾,下载脚本,并以 .js 命名,另一个同样操作  。分析第二个脚本文件,可以看到TreeView的很多客户端函数,其中关键的一个 TreeView_ToggleNode 就是客户端点击时触发的事件  。

  要想做个性化的操作,就得从 TreeView_ToggleNode 事件下手  。我们无法更改.net封装好的脚本,只有“重写”  。所谓的重写就是在原来的函数之后添加一个同名函数(因为js对于同名函数只调用最后一个)  。

  TreeView_ToggleNode 的原函数:

  1. function TreeView_ToggleNode(data, index, node, lineType, children) {  
  2. var img = node.childNodes[0];  
  3. var newExpandState;  
  4. try {  
  5. if (children.style.display == "none") {  
  6. children.style.display = "block";  
  7. newExpandState = "e";  
  8. if ((typeof(img) != "undefined") && (img != null)) {  
  9. if (lineType == "l") {  
  10. img.src = data.images[15];  
  11. }  
  12. else if (lineType == "t") {  
  13. img.src = data.images[12];  
  14. }  
  15. else if (lineType == "-") {  
  16. img.src = data.images[18];  
  17. }  
  18. else {  
  19. img.src = data.images[5];  
  20. }  
  21. img.alt = data.collapseToolTip.replace(/\{0\}/, TreeView_GetNodeText(node));  
  22. }  
  23. }  
  24. else {  
  25. children.style.display = "none";  
  26. newExpandState = "c";  
  27. if ((typeof(img) != "undefined") && (img != null)) {  
  28. if (lineType == "l") {  
  29. img.src = data.images[14];  
  30. }  
  31. else if (lineType == "t") {  
  32. img.src = data.images[11];  
  33. }  
  34. else if (lineType == "-") {  
  35. img.src = data.images[17];  
  36. }  
  37. else {  
  38. img.src = data.images[4];  
  39. }  
  40. img.alt = data.expandToolTip.replace(/\{0\}/, TreeView_GetNodeText(node));  
  41. }  
  42. }  
  43. }  
  44. catch(e) {}  
  45. datadata.expandState.value =  data.expandState.value.substring(0, index) + 
    newExpandState + data.expandState.value.slice(index + 1);