I am currently developing a project using ASP.NET Core and encountering an issue with populating a Bootstrap treeview from an AJAX call. I am able to retrieve the response from the server, but the tree view is not being created on the page.
After installing the necessary package via npm and linking the CSS and script files, here is the relevant code snippet:
<div class="row">
<label for="treeview"></label>
<div id="treeview" />
</div>
function getTree() {
$.ajax({
type: 'GET',
url: '/Home/GetTreeNodes',
dataType: "json",
})
.done(function (response) {
$("#treeview").treeview({ data: response })
console.log(response);
})
.fail(function (response) {
console.log(response);
});
}
getTree();
Below is the JSON action method in my controller:
[HttpGet]
public JsonResult GetTreeNodes(string query)
{
// Retrieve tree nodes from database
List<TreeNodes> treeNodes;
// Tree node view model
List<TreeNodesViewModel> treeNodesViewModel;
treeNodes = _context.TreeNodes.ToList();
if (!string.IsNullOrWhiteSpace(query))
{
treeNodes = treeNodes.Where(q => q.Name.Contains(query)).ToList();
}
treeNodesViewModel = treeNodes.Where(l => l.ParentId == null)
.Select(l => new TreeNodesViewModel
{
Text = l.Name,
Id = l.Id,
ParentId = l.ParentId,
@Checked = l.Checked,
Children = GetChildren(treeNodes, l.Id)
}).ToList();
return Json(treeNodesViewModel);
}
private List<TreeNodesViewModel> GetChildren(List<TreeNodes> nodes, int parentId)
{
return nodes.Where(l => l.ParentId == parentId).OrderBy(l => l.OrderNumber)
.Select(l => new TreeNodesViewModel
{
Text = l.Name,
Id = l.Id,
ParentId = l.ParentId,
@Checked = l.Checked,
Children = GetChildren(nodes, l.Id)
}).ToList();
}
Currently, only the root node is displayed on the view:
https://i.sstatic.net/r5sWV.png
I would greatly appreciate any assistance in resolving this issue. Despite searching online for examples and help, I have not been able to find a solution that addresses why this problem is occurring.