.NET 6中如何实现ProductCategorie与ProductSubCategorie级联下拉?
实现分类与子分类的级联下拉功能
基于你已有的代码结构,只需完成以下几步就能实现级联下拉功能:
一、新增后端API接口用于动态获取子分类
在ProductController.cs中添加一个接口,接收分类ID并返回对应的子分类列表:
[HttpGet] public async Task<IActionResult> GetSubCategories(long categorieId) { try { var subCategories = await _iCommon.LoadddlProductSubCategorieByCategorieId(categorieId) .ToListAsync(); return Json(subCategories); } catch (Exception ex) { return StatusCode(500, "加载子分类失败"); } }
二、修改初始视图的子分类加载逻辑
在ProductController.cs的AddEdit方法中,初始加载时不再传递所有子分类,只保留空的下拉选项(子分类将通过API动态加载):
// 替换原有的ViewBag._LoadddlProductSubCategorie赋值 ViewBag._LoadddlProductSubCategorie = new SelectList(new List<ItemDropdownListViewModel>(), "Id", "Name");
三、前端添加级联交互逻辑
在_Add.cshtml的末尾添加JavaScript代码,监听分类下拉框的选择变化,动态更新子分类选项:
<script> const categorySelect = document.getElementById('Category'); const subCategorySelect = document.getElementById('SubCategory'); categorySelect.addEventListener('change', async function() { const categoryId = this.value; // 清空子分类,保留默认提示选项 subCategorySelect.innerHTML = '<option disabled selected>--- SELECT ---</option>'; if (categoryId) { try { // 调用后端API获取对应子分类 const response = await fetch(`/Product/GetSubCategories?categorieId=${categoryId}`); const subCategories = await response.json(); // 动态生成子分类选项 subCategories.forEach(item => { const option = document.createElement('option'); option.value = item.Id; option.textContent = item.Name; subCategorySelect.appendChild(option); }); } catch (err) { console.error('加载子分类出错:', err); } } }); </script>
四、处理编辑页面的子分类回显
如果是编辑已有产品,需要在AddEdit方法的编辑分支中,根据产品的分类ID预先加载对应子分类并选中原有值:
if (id > 0) { vm = await _context.Product.Where(x => x.Id == id).SingleOrDefaultAsync(); vm.listCommentCRUDViewModel = await _iCommon.GetCommentList(id).ToListAsync(); // 加载当前分类对应的子分类,并选中产品原有的子分类 ViewBag._LoadddlProductSubCategorie = new SelectList( await _iCommon.LoadddlProductSubCategorieByCategorieId(vm.Category), "Id", "Name", vm.SubCategory ); return PartialView("_Edit", vm); }
内容的提问来源于stack exchange,提问作者Durlove Roy
相关产品推荐
相关产品推荐

