In this article I will explain with an example, how to populate
jsTree from database using
jQuery in ASP.Net using C# and VB.Net.
HTML Markup
The HTML Markup consists of following controls:
div – For generating the
jQuery TreeView.
HiddenField – For storing selected items.
Button – For displaying selected items.
The Button has been assigned with an OnClick event handler.
<div id="jstree"></div>
<asp:HiddenField runat="server" ID="selectedItems" />
<asp:Button runat="server" Text="Submit" OnClick="OnSubmit" />
jQuery TreeView implementation
Inside the HTML Markup, the following CSS file is inherited.
1. style.min.css
And then, the following JS files are inherited.
1. jquery.min.js
2. jstree.min.js
Inside the
jQuery document ready event handler, the
jQuery jsTree plugin is applied to the HTML DIV.
core – It is used to store all defaults for the core.
checkbox – It is used to store all defaults for the CheckBox.
plugins – It is used to configure which plugins will be loaded. It should be an array of strings, where each element is a plugin name. The default is [].
The core has following properties:-
themes – This property is used to configuration the theme object for the
jQuery jsTree plugin.
data – This property is used to configuration the data for the
jQuery jsTree plugin.
Then, inside the
data property, using a
function jQuery AJAX call is made to the
WebMethod which returns the Generic List collection of
TreeViewNode class.
The function accepts two arguments.
1. obj – It specifies that the node being loaded.
2. cb – The callback function to call the children for the node.
Inside the
AJAX Success event handler, the received response is passed to the
call function of the
callback argument which in turns populates the child nodes.
changed.jstree
Inside the
changed event handler of the
jQuery jsTree plugin, an Array is declared.
Then, a FOR loop is executed over the selected (checked) items of
jsTree and inserted into the Array one by one.
Finally, the Array of
JSON objects is serialized and saved in the Hidden Field.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<script type="text/javascript">
$(function () {
$('#jstree').on('changed.jstree', function (e, data) {
var i, j;
var selectedItems = [];
for (i = 0, j = data.selected.length; i < j; i++) {
//Fetch the Id.
var id = data.selected[i];
//Remove the ParentId.
if (id.indexOf('-') != -1) {
id = id.split("-")[1];
}
//Add the Node to the JSON Array.
selectedItems.push({
text: data.instance.get_node(data.selected[i]).text,
id: id,
parent: data.selected[i].split("-")[0]
});
}
//Serialize the JSON Array and save in HiddenField.
$('[id*=selectedItems]').val(JSON.stringify(selectedItems));
}).jstree({
"core": {
"themes": { "variant": "large" },
//Using function to make Ajax Call.
"data": function (obj, cb) {
$.ajax({
url: "Default.aspx/GetData",
type: "POST",
data: {},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
//The callback function.
cb.call(this, data.d);
},
error: function (response) {
alert(response.responseText);
}
});
}
},
"checkbox": { "keep_selected_style": false },
"plugins": ["wholerow", "checkbox"]
});
});
</script>
Namespaces
You will need to import the following namespaces.
C#
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using System.Web.Script.Serialization;
VB.Net
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
Imports System.Web.Script.Serialization
Property Class
The class consists of following properties.
C#
public class TreeViewNode
{
public string id { get; set; }
public string parent { get; set; }
public string text { get; set; }
}
VB.Net
Public Class TreeViewNode
Public Property id As String
Public Property parent As String
Public Property text As String
End Class
Server Side WebMethod
First, a Generic List collection of TreeViewNode class is created.
Then, the records from the database are fetched using DataReader (SqlDataReader) and added to a Generic List collection of TreeViewNode class.
Finally, the Generic List collection of TreeViewNode class are returned.
C#
[WebMethod]
public static List<TreeViewNode> GetData()
{
List<TreeViewNode> nodes = new List<TreeViewNode>();
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM VehicleTypes;SELECT Id, Name, VehicleTypeId FROM VehicleSubTypes", con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
nodes.Add(new TreeViewNode
{
id = sdr["Id"].ToString(),
parent = "#",
text = sdr["Name"].ToString()
});
}
sdr.NextResult();
while (sdr.Read())
{
nodes.Add(new TreeViewNode
{
id = sdr["VehicleTypeId"].ToString() + "-" + sdr["Id"].ToString(),
parent = sdr["VehicleTypeId"].ToString(),
text = sdr["Name"].ToString()
});
}
}
con.Close();
}
}
return nodes;
}
VB.Net
<WebMethod>
Public Shared Function GetData() As List(Of TreeViewNode)
Dim nodes As List(Of TreeViewNode) = New List(Of TreeViewNode)()
Dim constring As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constring)
Using cmd As SqlCommand = New SqlCommand("SELECT Id, Name FROM VehicleTypes;SELECT Id, Name, VehicleTypeId FROM VehicleSubTypes", con)
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
nodes.Add(New TreeViewNode With {
.id = sdr("Id").ToString(),
.parent = "#",
.text = sdr("Name").ToString()
})
End While
sdr.NextResult()
While sdr.Read()
nodes.Add(New TreeViewNode With {
.id = sdr("VehicleTypeId").ToString() & "-" + sdr("Id").ToString(),
.parent = sdr("VehicleTypeId").ToString(),
.text = sdr("Name").ToString()
})
End While
End Using
con.Close()
End Using
End Using
Return nodes
End Function
Submitting the Form
When
Submit button is clicked, the serialized
JSON string is retrieved from HiddenField and deserialize into Generic List collection of
TreeViewNode class using the
Deserialize method of
JavaScriptSerializer class.
C#
protected void OnSubmit(object sender, EventArgs e)
{
List<TreeViewNode> items = new JavaScriptSerializer().Deserialize<List<TreeViewNode>>(selectedItems.Value);
}
VB.Net
Protected Sub OnSubmit(ByVal sender As Object, ByVal e As EventArgs)
Dim items As List(Of TreeViewNode) = New JavaScriptSerializer().Deserialize(Of List(Of TreeViewNode))(selectedItems.Value)
End Sub
Screenshots
The jQuery TreeView
TreeView selected Nodes
Downloads