在ASP.NET中实现树形结构的节点分组,可以通过以下步骤来完成:
public class TreeNode
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string Name { get; set; }
public List<TreeNode> Children { get; set; }
public TreeNode()
{
Children = new List<TreeNode>();
}
}
public class TreeDataAccess
{
private readonly ApplicationDbContext _context;
public TreeDataAccess(ApplicationDbContext context)
{
_context = context;
}
public async Task<IEnumerable<TreeNode>> GetAllAsync()
{
return await _context.TreeNodes.ToListAsync();
}
public async Task<TreeNode> GetByIdAsync(int id)
{
return await _context.TreeNodes.FindAsync(id);
}
public async Task AddAsync(TreeNode node)
{
_context.TreeNodes.Add(node);
await _context.SaveChangesAsync();
}
public async Task UpdateAsync(TreeNode node)
{
_context.TreeNodes.Update(node);
await _context.SaveChangesAsync();
}
public async Task DeleteAsync(int id)
{
var node = await _context.TreeNodes.FindAsync(id);
if (node != null)
{
_context.TreeNodes.Remove(node);
await _context.SaveChangesAsync();
}
}
}
[ApiController]
[Route("api/[controller]")]
public class TreeController : ControllerBase
{
private readonly TreeDataAccess _treeDataAccess;
public TreeController(TreeDataAccess treeDataAccess)
{
_treeDataAccess = treeDataAccess;
}
[HttpGet]
public async Task<IActionResult> Get()
{
var treeNodes = await _treeDataAccess.GetAllAsync();
var groupedNodes = GroupNodesByParentId(treeNodes);
return Ok(groupedNodes);
}
private static Dictionary<int, List<TreeNode>> GroupNodesByParentId(IEnumerable<TreeNode> nodes)
{
var groupedNodes = new Dictionary<int, List<TreeNode>>();
foreach (var node in nodes)
{
if (!groupedNodes.ContainsKey(node.ParentId))
{
groupedNodes[node.ParentId] = new List<TreeNode>();
}
groupedNodes[node.ParentId].Add(node);
}
return groupedNodes;
}
}
@page "/tree"
@model List<TreeNode>
<ul>
@foreach (var group in Model.GroupBy(n => n.ParentId))
{
<li>
@group.Key
<ul>
@foreach (var node in group)
{
<li>@node.Name</li>
}
</ul>
</li>
}
</ul>
这样,你就可以在ASP.NET中实现树形结构的节点分组了。