'Use C# string as parameter in JQuery tree

Good day. I have a tree in my MVC view, where I can add in nodes like so:

<script type="text/javascript">
    $('#jstree_demo').jstree({
        'core': {
            'data': [
                { "id" : "ajson1", "parent" : "#", "text" : "Simple root node" },
                { "id" : "ajson2", "parent" : "#", "text" : "Root node 2" },
                { "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" },
                { "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" },
            ]
        }
    });
</script>

Which yields the following:

enter image description here

However, I want to add in nodes dynamically from a database.

I tried formatting a string in place of the data parameter like so:

            'data': [
                @Html.Raw(Json.Encode(jsonString));
            ]

Where jsonString is created via a foreach loop that takes the values from my model and combines them to give something like:

               "{ \"id\" : \"ajson1\", \"parent\" : \"#\", \"text\" : \"Simple root node\" },
                { \"id\" : \"ajson2\", \"parent\" : \"#\", \"text\" : \"Root node 2\" },
                { \"id\" : \"ajson3\", \"parent\" : \"ajson2\", \"text\" : \"Child 1\" },
                { \"id\" : \"ajson4\", \"parent\" : \"ajson2\", \"text\" : \"Child 2\" },"

This resulted in a very nasty result of:

enter image description here

I then tried manipulating the string in all sorts of ways to try to make this work, but to no avail.

I tried looking at the documentation to find a way to add in nodes one by one, but was unable to figure it out.

Is there any way for this to work without using Ajax?

Thanks in advance.

For reference, I used jsTree.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source