Home >Web Front-end >JS Tutorial >ASP.NET tree implementation code based on JQuery_jquery

ASP.NET tree implementation code based on JQuery_jquery

WBOY
WBOYOriginal
2016-05-16 18:15:011077browse

The data of this tree is extracted from the sql table. The structure of the sql table is as follows:

In the above table, parentmodeuleID is a sign representing the parent ID. If the current node is the root node, it is specified as 0.

Then the next step is how to form a tree structure with the above single table. At this time, we can use IList to load database models to achieve this. The specific Tree class is as follows:

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


namespace RolePermission1
{
 public class Tree
 {
  public int ModuleID { get; set; }

  public int ParentID { get; set; }

  public string ModulePath { get; set; }

  public string ModuleName { get; set; }

  
 }
}

Then the database data is organized on the public processing page to form a json format that conforms to jquery tree. The specific code is as follows:

[WebMethod]
  public static string GetJson()
  {
   string json = "[";
   IList<Tree> t = DB.returnParentTree();
   foreach (Tree model in t)
   {
    if (model != t[t.Count - 1])
    {
     json += GetJsonByModel(model) + ",";
    }
    else
    {
     json += GetJsonByModel(model);
    }
   }
   json += "]";
   json=json.Replace("'","\"");
   return json;
  }

  public static string GetJsonByModel(Tree t)
  {
   string json = "";
   bool flag = DB.isHaveChild(t.ModuleID);

   json = "{"
      + "'id':'" + t.ModuleID + "',"
      + "'text':'" + t.ModuleName + "',"
      + "'value':'" + t.ModuleID + "',"
      + "'showcheck':true,"
      + "'checkstate':'0',"
      + "'hasChildren':" + flag.ToString().ToLower() + ","
      + "'isexpand':false,"
      + "'ChildNodes':"; /*奶奶的,这个地方一定要注意是ChildNodes 而不是childNodes 害得我无语了*/
   if (!flag)
   {
    json += "null,";
    json += "'complete':false}";
   }
   else
   {
    json += "[";
    IList<Tree> list = DB.getChild(t.ModuleID);
    foreach (Tree tree in list)
    {
     if (tree != list[list.Count - 1])
     {
      json += GetJsonByModel(tree) + ",";
     }
     else
     {
      json += GetJsonByModel(tree);
     }
    }
    json += "],'complete':true}";
   }
   return json;
  }

The above is to use recursion to combine database data into appropriate json data. The database operation code used is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace RolePermission1
{
 public class DB
 {

  public static readonly string connStr=System.Configuration.ConfigurationManager.AppSettings["connStr"];

  public static SqlConnection GetConn()
  {
   SqlConnection conn = new SqlConnection(connStr);
   conn.Open();
   return conn;
  }

  public static DataTable GetDT(string sql)
  {
   DataTable dt = new DataTable();
   using (SqlConnection conn = DB.GetConn())
   {
    SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
    sda.Fill(dt);
   }
   return dt;
  }

  public static IList<Tree> returnParentTree()
  {
   IList<Tree> t = new List<Tree>();
   string sql = "select * from Models where [ParentModuleID]=0 order by OrderBy asc";
   DataTable dt = GetDT(sql);
   foreach (DataRow dr in dt.Rows)
   {
    Tree tParent = new Tree();
    tParent.ModuleID = Int32.Parse(dr["ID"].ToString());
    tParent.ModuleName = dr["ModuleName"].ToString();
    tParent.ModulePath = dr["MenuPath"].ToString();
    tParent.ParentID = Int32.Parse(dr["ParentModuleID"].ToString());
    t.Add(tParent);
   }
   return t;
  }

  public static bool isHaveChild(int id)
  {
   bool flag=false;
   string sql = "select ID from Models where ParentModuleID="+id+"";
   DataTable dt = GetDT(sql);
   if (dt.Rows.Count > 0)
   {
    flag = true;
   }
   return flag;
   
  }
  public static IList<Tree> getChild(int id)
  {
   IList<Tree> t = new List<Tree>();
   string sql = "select * from Models where ParentModuleID=" + id + "";
   DataTable dt = GetDT(sql);
   foreach (DataRow dr in dt.Rows)
   {
    Tree tParent = new Tree();
    tParent.ModuleID = Int32.Parse(dr["ID"].ToString());
    tParent.ModuleName = dr["ModuleName"].ToString();
    tParent.ModulePath = dr["MenuPath"].ToString();
    tParent.ParentID = Int32.Parse(dr["ParentModuleID"].ToString());
    t.Add(tParent);
   }
   return t;
  }

 }
}

Okay, after the json data is processed, you can hit the json to the front desk and hand it over to jquery for processing,

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RolePermission1._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>
 <script src="jquery.treeview/lib/jquery.js" type="text/javascript"></script>
 <link href="jquery.treeview/tree.css" rel="stylesheet" type="text/css" />
 <script src="jquery.treeview/common.js" type="text/javascript"></script>
 <script src="jquery.treeview/jquery.tree.js" type="text/javascript"></script>
</head>
<body>
 <form id="form1">
  <button id="showchecked" runat="server">Get Selected Nodes</button>
 <div id="showTree" class="filetree">
 </div>
 </form>
</body>
 <script type="text/javascript">
  $(document).ready(function() {
  $.ajax({
   type: "post",
   contentType: "application/json;charset=utf-8",
   dataType: "json",
   url: "WebForm1.aspx/GetJson",
   success: function(data) {
    var o = { showcheck: true };
    o.data = eval(data.d);
    $("#showTree").treeview(o);
   }
   });
 });
 $("#showchecked").click(function(e) {
  var s = $("#showTree").getTSVs();
  if (s != null)
   alert(s.join(","));
  else
   alert("NULL");
 });
 </script>
</html>

Okay, let’s take a look at the loading results:


Things to pay attention to during the production process are: first, the recursion must be correct; secondly, pay attention to the js capitalization ('ChildNodes' was written as 'childNodes' by me, and it took me a day to adjust it); thirdly, the public page can be called directly method, just add the [webmethod] mark in front of the method.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn