首页 > 解决方案 > 如何在 asp.net core mvc 中制作级联下拉菜单?

问题描述

我之前曾尝试过,但无法成功。

谁能举例告诉我?

标签: asp.net-coreasp.net-core-mvc

解决方案


您可以参考以下步骤在 asp.net core MVC 中创建级联下拉菜单。

  1. 创建具有关系的模型:

     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; }
     }
    
  2. 然后使用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;
         }
     }
    
  3. 在 Startup.ConfigureServices 方法中注册服务:

         services.AddTransient<IRepository, Repository>();
    
  4. 然后,在 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();
         }
    
  5. 视图页面(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>
     }
    

截图如下:

在此处输入图像描述


推荐阅读