ASP.NET Core 8.0 MVC : .jsTree hierarchy menu from SQL Server database

32 Views Asked by At

I have tried to make some hierarchy structure to navigate partial views. I have used older versions to create this tree in .NET 8.0, but it helped me to create just 1st row in tree, whenever I called method GetChildren, it blows up and throws errors about memory leak.

Does anybody know what is wrong with this controller?

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using 2024.Models;
using 2024.Data;

public class HomeController : Controller
{
    private readonly DbTestContext _db;

    public HomeController(DbTestContext db)
    {
        _db = db;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public IActionResult GetTreeNodes()
    {
        var treeNodes = _db.KJedinicas
                           .Where(j => j.Idparent == null)
                           .Select(j => new
                                        {
                                            id = j.Id.ToString(),
                                            parent = "#",
                                            text = j.Name,
                                            state = new
                                                    {
                                                        opened = false
                                                    },
                                            children = GetChildren(j.Id)
                                        });

        return Json(treeNodes);
    }

    private IEnumerable<object> GetChildren(int parentId)
    {
        var childrenData = _db.Categories
                              .Where(k => k.Idparent == parentId)
                              .Select(k => new
                                           {
                                               id = k.Id.ToString(),
                                               parent = k.Idparent.ToString(),
                                               text = k.Name,
                                               state = new { opened = false },
                                               children = GetChildren(k.Id)
                                           }).ToList();

        return childrenData;
    }

    [HttpGet]
    public IActionResult PartialViewWithData(int? id)
    {
        var model = _db.KTables.FirstOrDefault(j => j.Id == id);
        return PartialView("_PartialViewWithData", model);
    }
}

I was expecting that he shows me levels for this structure however many there are but he displayed only 1st level for 1st function, and 2nd doesn't work.

I think I made a mistake when I call 2nd function and when I send list or enumerable to the 1st, but I don't have idea to change it...

Thank you

0

There are 0 best solutions below