0

我使用 ASP.NET Core 并尝试从 ajax 调用填充引导树视图。我可以从服务器获得响应,但树视图不会在视图上创建树。

我已经通过 npm 安装了包并链接到 css 和脚本。这是视图:

<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();

这是我的控制器中的 Json 操作:

 [HttpGet]
    public JsonResult GetTreeNodes(string query)
    {
        // Tree nodes from db
        List<TreeNodes> treeNodes;
        // Tree nodes 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();
    }

视图上唯一显示的是根节点:

根节点

任何帮助将不胜感激,一直在网上搜索示例和帮助,但没有找到任何说明我为什么会遇到这个问题的东西。

4

1 回答 1

0

Just in case somebody in the future stumbles across this i figured it out. My code was fine, i had to change the structure of the viewmodel with text first and also change the name of children to nodes then it worked fine.

On a side note, i have tried running this with bootstrap 4 alpha 6 and it doesn't show the checkboxes. So use it as stated on the site with bootstrap <= 3.

于 2018-02-16T17:46:37.637 回答