繁体   English   中英

如何在 asp.net 核心 mvc 中制作级联下拉菜单?

[英]How to make Cascading dropdown in asp.net core mvc?

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

谁能举例告诉我?

您可以参考以下步骤在 asp.net 核心 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 controller 中,使用以下代码获取类别和子类别:

     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> }

截图如下:

在此处输入图像描述

这在 ASP.Net Core 中应该没有什么特别之处,因为视图仍然是从基本的 HTML 和 CSS 构建的,您可以使用 JS。

我建议您按照 W3Schools 中关于该主题的教程:https://www.w3schools.com/howto/howto_js_cascading_dropdown.asp

如您所见,在教程中使用这个嵌套数组作为下拉数据:

var subjectObject = {
  "Front-end": {
    "HTML": ["Links", "Images", "Tables", "Lists"],
    "CSS": ["Borders", "Margins", "Backgrounds", "Float"],
    "JavaScript": ["Variables", "Operators", "Functions", "Conditions"] 
  },
  "Back-end": {
    "PHP": ["Variables", "Strings", "Arrays"],
    "SQL": ["SELECT", "UPDATE", "DELETE"]
  }
}

如果您的下拉数据是 static 您可以直接将其放入 JS 代码中,但我建议在服务器端生成它,然后:

  1. 将其作为视图数据传递,将其序列化为 json 并用您的文字 json 字符串替换 JS 代码中的数组初始化
  2. 从客户端向服务器(例如使用 XHR)向某种 API 端点发出第二个请求,并将下拉数据加载为 json,然后对其进行反序列化并将数据放入下拉数据数组中。 (在这种情况下不要忘记重新加载实际的下拉元素选项)

如果某些事情不容易理解,请随时要求澄清。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM