在ASP.NET Core中实现多级分类可以使用树状结构的数据模型。以下是一个包含代码示例的解决方法:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public Category Parent { get; set; }
public List Children { get; set; }
}
public class ApplicationDbContext : DbContext
{
public DbSet Categories { get; set; }
// 其他代码...
}
public class CategoryService
{
private readonly ApplicationDbContext _context;
public CategoryService(ApplicationDbContext context)
{
_context = context;
}
public List GetCategories()
{
return _context.Categories.Include(c => c.Children).ToList();
}
public void AddCategory(Category category)
{
_context.Categories.Add(category);
_context.SaveChanges();
}
// 其他操作方法...
}
public class CategoryController : Controller
{
private readonly CategoryService _categoryService;
public CategoryController(CategoryService categoryService)
{
_categoryService = categoryService;
}
public IActionResult Index()
{
var categories = _categoryService.GetCategories();
return View(categories);
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Category category)
{
if (ModelState.IsValid)
{
_categoryService.AddCategory(category);
return RedirectToAction("Index");
}
return View(category);
}
// 其他操作方法...
}
@model List
Categories
@foreach (var category in Model.Where(c => c.ParentId == null))
{
-
@category.Name
@Html.Partial("_SubCategories", category)
}
@model Category
@if (Model.Children.Any())
{
@foreach (var subCategory in Model.Children)
{
-
@subCategory.Name
@Html.Partial("_SubCategories", subCategory)
}
}
通过以上步骤,你就可以在ASP.NET Core应用程序中实现多级分类了。