1

I am using bootstrap-treeview to build my tree view.

I need to pass an array of JavaScript objects as data, to bootstrap-treeview.

I have defied a tree structure on the server side to build the tree and serialize it into a Json string. I then pass the Json string to client via an AJAX call:

// Tree object
public class MyTree
{
    public string text { get; set; }
    public List<MyTree> nodes { get; set; }
}

// I build the tree, and serialize it like this to be returned to JavaScript like this:
return JsonConvert.SerializeObject(treeObject);

This is my JavaScript code for building the tree. I want to pass the tree as data to bootstrap-treeview:

function getTree() {
    $.getJSON("/api/GetTree", function (tree) {
        return tree;

        // I have tried this as well but did not work:
        // var res = JSON.parse(tree);
        // return res;
    });
}

$('#MyTree').treeview({
    data: getTree(),
    enableLinks: true,
    showBorder: false
});

And this is the Screenshot from the value that I receive from the server in the AJAX call:

Chrome debugger screenshot

As seen above, I also tried passing: JSON.parse(tree); but it did not display the data either.

  • It is obvious that bug is there in the server side code, where you are creating the MyTree object. show the code where treeObject is being created. – Sandip Ghosh Jan 10 '18 at 06:23
  • Thanks Sandip, the server side is returning the expected data, if you look at the screenshot at the end of question, it shows the content of tree structure being returned from the tree. –  Jan 10 '18 at 06:32

1 Answers1

1

Edit and try with this :

function getTree() {
    $.getJSON("/api/GetTree", function (tree) {
      $('#MyTree').treeview({
        data: tree,
        enableLinks: true,
        showBorder: false
      });
        // I have tried this as well but did not work:
        // var res = JSON.parse(tree);
        // return res;
    });
}

getTree();
Gitesh Purbia
  • 1,094
  • 1
  • 12
  • 26
  • Thanks a lot, it worked. Can you please explain how this is different from the way I was passing the object? –  Jan 10 '18 at 06:31
  • in your case, getTree is the asynchronous function, so it will call when your api request give response. So when you call $('#MyTree').treeview({}) at that time data is not fetched from your api, data: getTree(), because getTree() is a asynchronous function. – Gitesh Purbia Jan 10 '18 at 06:34