Hi,
after some days of trying I finally managed to display a TreeView by transforming database entries to a treeview structure and pass it to the view inside a viewmodel.
Model:
View:
Controller:
public TreeNodesStruct RecursiveTreeChildGetter(TreeNodesStruct root, ICollection<
LibraryTreeNode
> allNodes)
{
var childs = allNodes.Where(n => n.ParentNodeId == root.LibraryTreeNodeId);
if (childs != null && childs.ToList().Count > 0)
{
if (root.ChildNodes == null)
{
root.ChildNodes = new List<
TreeNodesStruct
>();
}
foreach (LibraryTreeNode child in childs)
{
TreeNodesStruct treeChild = new TreeNodesStruct();
treeChild.ChildNodes = new List<
TreeNodesStruct
>();
treeChild.LibraryTreeNodeId = child.LibraryTreeNodeId;
treeChild.Title = child.Title;
treeChild.ParentNodeId = child.ParentNodeId;
root.ChildNodes.Add(treeChild);
treeChild.ChildNodes = RecursiveTreeChildGetter(treeChild, allNodes).ChildNodes;
}
}
return root;
}
public ActionResult LibraryTreePartial()
{
List<
TreeNodesStruct
> tree = new List<
TreeNodesStruct
>();
ICollection<
LibraryTreeNode
> nodes = libraryTreeNodeService.GetAllItems();
var roots = nodes.Where(n => n.ParentNodeId == null);
foreach (LibraryTreeNode root in roots)
{
TreeNodesStruct treeRoot = new TreeNodesStruct();
treeRoot.ChildNodes = new List<
TreeNodesStruct
>();
treeRoot.LibraryTreeNodeId = root.LibraryTreeNodeId;
treeRoot.Title = root.Title;
treeRoot.ChildNodes = RecursiveTreeChildGetter(treeRoot, nodes).ChildNodes;
tree.Add(treeRoot);
}
var viewModel = new LibraryTreeFormModel();
viewModel.Tree = new List<
TreeNodesStruct
>();
viewModel.Tree = tree;
return View(viewModel);
}
I can get the selected node ID via javascript:
My question now is, how can I pass the selected node ID to the view model? I cannot do so in the javascript, for the model is not accessible within the script.
What I want to do is pass the selected node and the value from a textbox to the controller so that the user is able to create new subnodes. Any suggestions or workarounds?
Regards
Stefan