jsTree AJAX not calling MVC Controller

I am building a tree using the jsTree plugin with ASP.NET MVC 4. Here's my code before I elaborate:

HTML:

<div id="MainTree"></div>
<div onclick="$load();">Load Tree</div>

Javascript:

$load = function(){
    $('#MainTree').jstree({
        "json_data": {
            "ajax": {
                "url": "/Home/GetTreeData",
                "type": "POST",
                "dataType": "json",
                "contentType": "application/json charset=utf-8"
            }
        },
        "themes": {
            "theme": "default",
            "dots": false,
            "icons": true,
            "url": "/content/themes/default/style.css"
        },

        "plugins": ["themes", "json_data", "dnd", "contextmenu", "ui", "crrm"]

    });
}

Controller:

[HttpPost]
public JsonResult GetTreeData()
{
   JsTreeModel rootNode = new JsTreeModel(); // Breakpoint here, never triggered
   rootNode.attr = new JsTreeAttribute();
   rootNode.data = "Root";
   string rootPath = "Test";
   rootNode.attr.id = rootPath;

   JsTreeModel t1 = new JsTreeModel();
   t1.attr.id = "1";
   JsTreeModel t2 = new JsTreeModel();
   t2.attr.id = "2";
   JsTreeModel t3 = new JsTreeModel();
   t3.attr.id = "3";
   rootNode.children.Add(t1);
   rootNode.children.Add(t2);
   rootNode.children.Add(t3);

   return Json(rootNode);
}

When I click the "Load Tree" button, $load() is triggered and in Firefox debug it runs without throwing errors. The tree <div> changes from:

<div id="MainTree"></div>

to

<div role="tree" class="jstree jstree-1 jstree-default jstree-default-responsive jstree-leaf" id="MainTree">
<ul class="jstree-container-ul"></ul>
</div>

I placed a breakpoint in the Controller, noted in a comment, which never gets triggered; i.e. the call to the Controller never seems to be made. My HomeController.cs is without syntax errors.

Am I missing something here?

Upvotes: 1

Views: 1180

Answers (1)

I'll answer this myself rather than leave it as a orphan.

This is the easiest way I found to create a tree with jsTree:

<div id="divtree">
        <ul id="tree">
            <li>
                Subfolder 1
                <ul id="tree">
                    <li>Pub 1</li>
                    <li>Pub 2</li>
                    <li>Pub 3</li>
                </ul>
            </li>

            <li> 
                SubFolder 2
                <ul id="tree">
                    <li>Pub 1</li>
                    <li>Pub 2</li>
                </ul>
            </li>
        </ul>
    </div>

<script type="text/javascript">
    $(function(){
        $("#divtree").jstree();
    });
    </script>

Upvotes: 1

Related Questions