asp.net-core - 如何在 asp.net core mvc 中制作级联下拉菜单?
问题描述
我之前曾尝试过,但无法成功。
谁能举例告诉我?
解决方案
您可以参考以下步骤在 asp.net core MVC 中创建级联下拉菜单。
创建具有关系的模型:
public class Category { public int Id { get; set; } [Required] [Display(Name = "Category Name")] public string CategoryName { get; set; } public ICollection<SubCategory> SubCategories { get; set; } } public class SubCategory { public int Id { get; set; } [Required] [Display(Name = "SubCategory Name")] public string SubCategoryName { get; set; } public int CategoryID { get; set; } public Category Category { get; set; } }
然后使用EF核心迁移在数据库中创建相关表,或者创建一个服务来设置初始数据。在这里我创建了一个服务:
public interface IRepository { List<Category> GetCategories(); } public class Repository : IRepository { private readonly ApplicationDbContext db; public Repository(ApplicationDbContext context) { db = context; } //you can also query the database and get the data. public List<Category> GetCategories() { List<Category> categories = new List<Category>() { new Category(){ Id=101, CategoryName="Category 1", SubCategories= new List<SubCategory>(){ new SubCategory(){ Id=1001, SubCategoryName="SubCategory 1.1"}, new SubCategory(){ Id=1002, SubCategoryName="SubCategory 1.2"}, new SubCategory(){ Id=1003, SubCategoryName="SubCategory 1.3"}, } }, new Category(){ Id=102, CategoryName="Category 2", SubCategories= new List<SubCategory>(){ new SubCategory(){ Id=1001, SubCategoryName="SubCategory 2.1"}, new SubCategory(){ Id=1002, SubCategoryName="SubCategory 2.2"}, new SubCategory(){ Id=1003, SubCategoryName="SubCategory 2.3"}, } }, new Category(){ Id=103, CategoryName="Category 3", SubCategories= new List<SubCategory>(){ new SubCategory(){ Id=1001, SubCategoryName="SubCategory 3.1"}, new SubCategory(){ Id=1002, SubCategoryName="SubCategory 3.2"}, new SubCategory(){ Id=1003, SubCategoryName="SubCategory 3.3"}, } }, }; return categories; } }
在 Startup.ConfigureServices 方法中注册服务:
services.AddTransient<IRepository, Repository>();
然后,在 MVC 控制器中,使用以下代码获取类别和子类别:
public class HomeController : Controller { private readonly ApplicationDbContext _context; //db context. private readonly IRepository _repository; public HomeController( ApplicationDbContext context, IRepository repository) { _context = context; _repository = repository; } public IActionResult CreateIndex() { //get the categories. ViewBag.CategoryId = _repository.GetCategories().Select(c => new SelectListItem { Value= c.Id.ToString(),Text = c.CategoryName }).ToList(); return View(); } //get Subcategory based on the category id public IActionResult GetSubCategory(int cid) { var SubCategory_List = _repository.GetCategories().Where(s => s.Id == cid).FirstOrDefault().SubCategories.Select(c => new { Id = c.Id, Name = c.SubCategoryName }).ToList(); return Json(SubCategory_List); } [HttpPost] public IActionResult CreateIndex(ProductViewModel product) { return View(); }
视图页面(CreateIndex.cshtml)中的代码,页面加载时仅填充类别下拉列表,然后使用 JQuery 调用操作方法并填充子类别:
@model MVCDemo.Models.ProductViewModel @{ ViewData["Title"] = "CreateIndex"; } <div class="row"> <div class="col-md-4"> <form asp-action="CreateIndex"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="CategoryTypeId" class="control-label">Category Type</label> <select asp-for="CategoryTypeId" asp-items="ViewBag.CategoryId" class="form-control"> <option value="">Select Category</option> </select> </div> <div class="form-group"> <label asp-for="SubCategoryTypeId" class="control-label">SubCategory Type</label> <select asp-for="SubCategoryTypeId" class="form-control"></select> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div> </div> @section Scripts{ <script> $(function () { $("select#CategoryTypeId").change(function () { var cid = $(this).val(); $("select#SubCategoryTypeId").empty(); $.getJSON(`/Home/GetSubCategory?cid=${cid}`, function (data) { //console.log(data); $.each(data, function (i, item) { $("select#SubCategoryTypeId").append(`<option value="${item.id}">${item.name}</option>`); }); }); }) }); </script> }
截图如下:
推荐阅读
- mysql - 如何从 CSV 生成索引表?
- liferay - 无法为 Liferay 7.2-rc2 创建工作区
- python - 如何一次绘制不同产品的时间序列图?
- magento - Magento 2根据客户重定向到不同的商店视图
- java - 在 Android 上使用 Retrofit 解析嵌套的 json
- ios - 如何在 iOS 上使用具有透明度的 fontello 图标
- r - 是否有用于查找复数并计算它们的 R 函数?
- oracle - ORACLE:如何查找特定表中列对象的所有依赖项
- c# - 多个数据库提供程序的批量插入
- simple-injector - 简单注入器 .NET 标准 NuGet 包 PDB