I am using jsTree to display a tree structure of hierarchical data within my ASP.NET MVC application. So far, I am able to access the data (through a controller method which returns JSON data) and display the tree. I am also able to select nodes in the tree and that works correctly. Here is the jsTree code for doing this:
$('#tree').
bind('select_node.jstree', function(event, data) {
alert("Node is selected.");
}).
jstree({
"core": {},
"json_data": {
"ajax": {
type: 'POST',
url: '/Scenario/TreeData',
data: "id=" + <%= Model.Scenario.ScenarioID %>,
success: function(data, textStatus, xhr) {
if(data.failed) {
window.location.href = data.redirectToUrl;
}
}
}
},
"themes": {
"theme": "default",
"dots": true,
"icons": true
},
"ui": {
"select_limit": 1
},
"plugins": ["themes", "ui", "json_data"]
});
Here is my TreeData action:
[HttpPost]
public ActionResult TreeData(int id)
{
var tree = new JsTreeModel();
Scenario scenario = repository.GetScenario(id);
if (scenario != null)
{
tree.data = new JsTreeData();
// [snip] Do the work to build the tree. [/snip]
return Json(tree);
}
var jsonData = new
{
failed = true,
redirectToUrl = Url.Action("NotFound")
};
return Json(jsonData);
}
Where I am getting stuck is, once I click on a node, I am unsure of how to retrieve the data for that specific node from my application (via the Controller), display it (presumably in a partial view – all of which I have created at this time – strongly-typed partial views), and then offer the option to submit that partial view back to the server to update the data.
I’m not really sure where to begin. One thought I had is to expand my TreeModel class (C# model which makes it easier to build the JSON data for the tree) to take more parameters in the “data” value which may allow me to know which model I am attempting to retrieve. However, this doesn’t seem that elegant.
Am I missing something obvious? Does anybody have any other suggestions? Thank you!
I ended up figuring this out and wanted to share in case anybody else wants to do the same thing.
I first bound the select_node.jstree event to my tree and then built the tree (all done client-side, of course).
Notice that I am grabbing the URL value from the node. I had to change my JsTreeModel so that I could change the href value on the node. (JSON data representation is – data.attr.href) I set this value when I build my Scenario. Each node has its own URL. (I am passing the ID parameter in, so I can retrieve the correct Scenario server-side. That may or may not be necessary depending on your needs.)
I then create an action for each URL in my Controller. I do what I need to do with the data, and then return it back to the page (via the AJAX call shown previously). It’s actually a fairly simple solution now that I know what I am doing. But, due to a bit of lack of documentation, it was a bit tricky to first figure out.
Hope this can help someone else!