JsTree - populating tree dynamically using AJAX / C # web method

I have a div that I would like to populate with jsTree:

I am getting a Loading icon where the tree should be displayed, however there seems to be a javascript error even though it is not thrown.

I am loading folder structure from AJAX request as follows. The Documents.aspx / GetFolders web method returns a list containing the FolderId, ParentId, and folder name. I debugged the web method and passed the correct results to the jsTree "data" function.

$.ajax({
   type: "POST",
   url: 'Documents.aspx/GetFolders',
   contentType: "application/json; charset=utf-8",
   success: function (data) {
      data = data.d;

      $("#tree").jstree({
         "core": {
            "themes": {
               "responsive": true
            },
            "data": function () {
               var items = [];
               items.push({ 'id': "jstree_0", 'parent': "#", 'text': "Documents" });
               $(data).each(function () {
                  items.push({ 'id': "jstree_" + this.DocumentFolderId, 'parent': "jstree_" + this.ParentId, 'text': "" + this.Name });
               });
               return items;
            }
         },
         "types": {
            "default": {
               "icon": "fa fa-folder icon-lg"
            },
         },
         "plugins": ["contextmenu", "dnd", "state", "types"]
      });
   },
   error: function () {
      toastr.error('Error', 'Failed to load folders<span class=\"errorText\"><br/>There was a fatal error. Please contact support</span>');
   }
});

      

After debugging the code, it seems that the data is being fetched correctly and returning an array of objects as intended.

Are there any problems with the above (or is there somewhere else I should be looking for)? Or is there a better way to achieve the intended goal?

+3


source to share


2 answers


I think I finally found the answer! :)

"core": {
   "themes": {
      "responsive": true
   },
   "data": {
      type: "POST",
      url: "Documents.aspx/GetFolders",
      contentType: "application/json; charset=utf-8",
      success: function (data) {
         data.d;
         $(data).each(function () {
            return { "id": this.id };
         });
      }
   },
}

      



On the server side, you need to return the data in the required array format, for example:

[{id = "node0", parent = "#", text = "Documents"},
{id = "node1", parent = "node0", text = "Public"},
{id = "node2", parent = "node0", text = "Restricted"}]

      

+5


source


In case someone had a "loading ..." problem, this format fixed it when returning data.



[{"id":"node0", "parent":"#", "text":"Documents"},
{"id":"node1", "parent":"node0", "text":"Public"},
{"id":"node2", "parent":"node0", "text":"Public"}]

      

0


source







All Articles