kendoDropDownList cascade 2 cấp , cấp 1 chạy trước thì cấp 2 mới chạy
- User
kendoDropDownList cascade 2 cấp , cấp 1 chạy trước thì cấp 2 mới chạy
Assistant
Để tạo Kendo DropDownList cascade 2 cấp (cấp 1 chạy trước, cấp 2 chạy sau), bạn có thể làm như sau:
HTML Structure
<div> <label for="category">Danh mục:</label> <input id="category" /> </div> <div> <label for="product">Sản phẩm:</label> <input id="product" /> </div>JavaScript Implementation
$(document).ready(function() { // Khởi tạo DropDownList cấp 1 (Danh mục) $("#category").kendoDropDownList({ dataTextField: "CategoryName", dataValueField: "CategoryID", optionLabel: "Chọn danh mục...", dataSource: { transport: { read: { url: "/api/categories", // API lấy danh sách danh mục dataType: "json" } } }, change: function(e) { var categoryId = this.value(); var productDropDown = $("#product").data("kendoDropDownList"); if (categoryId) { // Cập nhật datasource cho dropdown cấp 2 productDropDown.setDataSource({ transport: { read: { url: "/api/products", data: { categoryId: categoryId }, // Truyền categoryId dataType: "json" } } }); productDropDown.enable(true); } else { // Reset dropdown cấp 2 nếu không chọn danh mục productDropDown.setDataSource([]); productDropDown.value(""); productDropDown.enable(false); } } }); // Khởi tạo DropDownList cấp 2 (Sản phẩm) - ban đầu disabled $("#product").kendoDropDownList({ dataTextField: "ProductName", dataValueField: "ProductID", optionLabel: "Chọn sản phẩm...", enabled: false, // Vô hiệu hóa ban đầu dataSource: [] // Datasource rỗng ban đầu }); });Cách hoạt động:
- DropDownList cấp 1 được khởi tạo với datasource từ API
/api/categories - DropDownList cấp 2 ban đầu bị vô hiệu hóa (
enabled: false) và có datasource rỗng - Khi người dùng chọn giá trị ở cấp 1, sự kiện
changeđược kích hoạt:- Lấy giá trị được chọn (
categoryId) - Cập nhật datasource cho dropdown cấp 2 với tham số
categoryId - Kích hoạt dropdown cấp 2
- Lấy giá trị được chọn (
- Nếu người dùng bỏ chọn cấp 1, dropdown cấp 2 sẽ được reset và vô hiệu hóa
API Backend mẫu:
// Controller cho Categories [HttpGet] public IActionResult GetCategories() { var categories = _context.Categories.Select(c => new { CategoryID = c.Id, CategoryName = c.Name }).ToList(); return Json(categories); } // Controller cho Products [HttpGet] public IActionResult GetProducts(int categoryId) { var products = _context.Products .Where(p => p.CategoryId == categoryId) .Select(p => new { ProductID = p.Id, ProductName = p.Name }).ToList(); return Json(products); }Cách này đảm bảo dropdown cấp 2 chỉ được kích hoạt và load dữ liệu sau khi người dùng đã chọn giá trị ở dropdown cấp 1.
- DropDownList cấp 1 được khởi tạo với datasource từ API
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.