Using Ajax in ASP.NET Core to implement a Bootstrap-treeview

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.

Answer №1

After some trial and error, I finally solved the issue that may come in handy for someone else down the road. The problem wasn't with my code itself, but rather with the structure of the viewmodel. I had to rearrange the text first and rename children to nodes before everything fell into place.

On a related note, I experimented with bootstrap 4 alpha 6 and encountered problems with checkboxes not displaying correctly. It's best to stick with versions equal to or below 3 as recommended on the Bootstrap website.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to transfer information via WebSocket when the connection closes in a React/NextJS application during a page reload or tab

In the development of my web application, I am implementing a feature to display the online/offline status of users. In order to achieve this functionality, I have to listen for both close and open events of the websocket. const ws = new WebSocket('ws ...

IdentityServer4 enables the storage and retrieval of data by utilizing the UserId

Incorporating IdentityServer4 results in the creation of various tables, including an AspNetUsers table that contains userIDs. I am interested in leveraging these userIDs to manage and access associated data. How can I extract the userID from a request wh ...

The dimensions of the upcoming data packet in the UDP queue

I am utilizing the System.Net.Sockets Socket class for receiving UDP datagrams. My goal is to determine the exact length of the received datagram so that I can verify its validity. The documentation for the Socket.Receive(Byte()) method states: If you ...

"Integrating `react-textarea-code-editor` with Remix: A Step-by-Step Guide

Upon loading the root of my web app, I encountered an error. The react-textarea-code-editor component is accessed via a separate route. The same error persisted even after following the suggestions provided here: Adding react-textarea-code-editor to the ...

Issue with the Select All checkbox functionality in an asp.net mvc project

https://i.sstatic.net/Y5ml2.png Here, I manually select checkboxes and press the sync button. When I do this individually, it works properly. However, if I press the select all button, all the checkboxes are selected but the sync process does not occur. ...

Navigating through various arrays within objects on a JSON API with JavaScript: A walkthrough

I am currently working on fetching and displaying data from an API. The specific data I am interested in is located within the 'equipments' array. You can see an example of this array in the image linked below: https://i.sstatic.net/QeBhc.jpg M ...

Node.js is powering the serving of HTML along with the execution of command-line operations and callback

I am trying to utilize Node.js to serve a single HTML file and respond to a request on the same port. In addition to serving the HTML page, I also want to run a local command to display the output of that command. However, I am encountering errors and unab ...

Is it possible for an AJAX call to fail, despite receiving a valid 200OK response?

There are times when the server responses return a 200OK status, but the content of the response is not what was anticipated. Is it possible to invoke the jquery ajax error callback even with a successful response, depending on certain criteria within the ...

Bespoke search functionality using AJAX and tags in WordPress

I have created a custom search form in my WordPress theme that looks like this: <form role="search" class="form" method="get" action="<?php echo home_url('/');?>"> <input type="search" id="keyword" class="inp-search" onclick="sh ...

Tips for resolving: Alert: React does not allow functions as a child component

I recently made an update to my router configuration to support a second main route. import React from 'react'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; // Components & Pages // Home import HomePag ...

Unlocking the potential of # to craft interactive web pages

Lately, I've been seeing more and more websites like Twitter that have integrated AJAX into their layouts. One thing that has really piqued my interest is the inclusion of #! in URLs. I'm curious about how I can implement this on my own site or w ...

unable to retrieve information from Laravel 5.4 controller for dynamic array of form input created with jQuery in the view file

I have implemented a form in the view file of my Laravel 5.4 app where additional input fields can be added using the jQuery clone() function. I have also incorporated the jQuery select2 plugin into this form. Here is the form: <form name="tempform" ac ...

Updating a nested subdocument within a subdocument in Mongoose

In my schema definition shown below, the UserSchema contains embedded Cards which in turn have many transactions. var TransactionSchema = new Schema({ merchantName: String, transactionTime: Date, latitude: Number, longitude: Number, amount: Numb ...

What can be done to stop the caching of the route that router.push() redirects to in Next.js middleware?

Encountering an issue with client-side navigation and middleware in the router. It seems that the router is storing the initial redirect path and subsequent navigations bypass the middleware. This behavior ceases upon browser refresh and does not occur in ...

I implemented a proxy in my project to handle cross-domain requests, however, the requested address changes when I make a

Unable to Cross Domains http://localhost:8080/api/login has to be redirected to http://localhost:8080/index.html proxyTable: { '/api': { target: 'http://47.106.74.67:8080', changeOrigin: true, pathRewrite: ...

Updating Model Property Value via AJAX Request

When I click on a table of data, I want to trigger a change. However, when I try to call the data in my initial model value (List), I encounter an error. POST https://localhost:7230/controller/List 404 This is My Controller [HttpGet] public async T ...

Incorporate additional form element functionalities using radio inputs

Recently, I created code that allows a user to duplicate form elements and add values by clicking on "add more". Everything is functioning properly except for the radio inputs. I am currently stuck on this issue. Does anyone have any suggestions on how I c ...

Implement a hover effect on a specific class targeting a nested element using JavaScript

Is there a method to apply a class that modifies rules for a child element using Javascript? I have successfully added it with CSS but am struggling to do the same with Javascript. Removing the class in JS is easy by referencing the classname before the ho ...

What is the best way to avoid the pipe symbol in jade formatting?

When working with jade, the pipe symbol (|) is utilized for displaying plain text. But what if you need to actually write it on the page? Is there a way to escape it in Jade? ...

Selenium not registering click on enabled element

I am trying to trigger a click event on an element on the page, but for some reason the Selenium click function is not working as expected. Here is the relevant code snippet: username_form = driver.find_element_by_id('form3-username') passwor ...