javascriptajaxc#-4.0jstreewebmethod

jsTree - Populate Tree Dynamically using AJAX/C#Web Method


I have a div which I would like to fill with a jsTree:

I get the "Loading" icon where the tree is meant to display, however, there would seem to be a javascript error, even though one is not thrown.

I load my folder structure from an AJAX Request as follows. The Documents.aspx/GetFolders Web Method returns a List containing FolderId, ParentId & Folder Name. I have debugged the web method and it is passing 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 the data is being retrieved correctly and is returning the object array as intended.

Is there are any problem with the above (or is there somewhere else I should be looking)? Or is there a better method of achieving its intended purpose?


Solution

  • I think I have 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 };
             });
          }
       },
    }
    

    Server side, you need to return the data in the array format required, i.e:

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