Sue
Sue

Reputation: 445

Creating jstree jquery_ajax in controller

I am using MVC3, Jquery, and jstree, my goal is to display the jstree with the help of json_data from the controller, I have researched this as much as I could but have not solved it, my problem is how to relate the function(n/node) to the action in the controller, and how to send the node list that I create in the controller action back to the view and parse the data, I will greatly appreciate any help or advise.

    <script type="text/javascript">



    $(function () {
        $("#demo1").jstree({
                "themes": {
                "theme": "default",
                "dots": true,
                "icons": false,
                "url": "/content/themes/default/style.css"
            },

            "json_data": {
                "ajax": {
                   "async": true,
                   "url": "/Home/GetItems",
                    "type": "POST",
                    "data": function (n) {
                        return { id: n.attr ? n.attr("id") : 0 }

                         "dataType": "text json",
                        "contentType": "application/json charset=utf-8",
                         "progressive_render": true
                    }
                }
            },
            "plugins": ["themes", "json_data", "dnd"]
        })
    });

and here is my controller code with the GetItems():

 [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult GetItems()
          {
        int cnt = 0;
        var itemRawData = (from ItemInfo itemtInfo in _itemInfoCollection
                       where itemInfo.Name == "val1" || itemInfo.Name == "val2"
                       select new itemSpecifications
                       {
                           itemName = itemInfo.Name,
                           itemVersion = itemInfo.MajorRevision.ToString() + "." + itemInfo.MinorRevision.ToString(),
                           iCount = ItemInfo.Count,
                           ilist = itemInfo.Values.Cast<subitem>().ToList(),
                           index = cnt++   });

        TreeNode node = new TreeNode();
        List<TreeNode> nodelist = new List<TreeNode>();
        foreach (var t in itemRawData)
        {
            nodelist.Add(new TreeNode
            {
            data = String.Format("{0} {1} ({2})",t.itemName, t.itemVersion, t.iCount.ToString()),
                state = "closed",
                children = t.ilist 

            });

        }
        return Json(nodelist);
    }

any example or advise will be greatly appreciated!

Upvotes: 1

Views: 7019

Answers (1)

CM Digital
CM Digital

Reputation: 331

I have created a simple demo using ASP.NET MVC3 and jstree. It loads the whole tree using ajax and it displays the node id and additional data when clicking on each node. Further information can be found in the json_data plugin documentation

View:

    <div id="demo1"></div>
    <script type="text/javascript">
        $(function () {
            $("#demo1").jstree({
                "themes": {
                    "theme": "classic",
                    "dots": false
                },
                "json_data": {
                    "ajax": {
                        "url": "/Controller/TreeViewTestContent",
                        "data": function (n) {
                            return { id: n.attr ? n.attr("id") : 0 };
                        } 
                    }
                },
                "plugins": ["themes", "json_data", "ui"]
            }).bind("select_node.jstree", function (event, data) {
                alert(data.rslt.obj.attr("id"));
                alert(data.rslt.obj.attr("other_attribute"));

            });
        });
    </script>

The controller that provides the tree view data:

public JsonResult TreeViewTestContent(string id)
        TreeViewItemModel aItem = new TreeViewItemModel();
        aItem.data = new TreeViewItemModelData
                     {
                         title = "Root Node", 
                         icon = "folder"
                     };
        aItem.attr = new TreeViewItemModelAttributes
                     {
                         id = "1",
                         other_attribute = "additional data can go here"
                     };
        aItem.state = "open";          

        List<TreeViewItemModel> aChildrenlist = new List<TreeViewItemModel>();
        TreeViewItemModel aChild = new TreeViewItemModel();
        aChild.data = new TreeViewItemModelData
        {
            title = "Child 1",
            icon = "folder",
        };
        aChild.attr = new TreeViewItemModelAttributes
                      {
                          id = "2",
                          other_attribute = "another value"
                      };
        aChildrenlist.Add(aChild);
        aItem.children = aChildrenlist;

        return Json(aItem,JsonRequestBehavior.AllowGet);
    }

and the Models

public class TreeViewItemModel
{
    public TreeViewItemModelData data { get; set; } 
    public string state { get; set; } //'open' to display node children when loaded, 'closed' to make an AJAX call to retrieve the children, 'string.empty' to not display the child nodes when loaded and do not make ajax calls to get the children
    public TreeViewItemModelAttributes attr { get; set; }
    public List<TreeViewItemModel> children { get; set; }
}

public class TreeViewItemModelData
{
    public string title { get; set; } //text do be displayed in the node
    public string icon { get; set; } //remove this property if not wanting to customize node icon

}

public class TreeViewItemModelAttributes
{
    public string id { get; set; }
    public string other_attribute { get; set; }
}

Hopefully it will be a good starting point for anyone using jstree.

Upvotes: 7

Related Questions