syncfusion-aspnetcore-dropdownlist
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseImplementing DropdownList in ASP.NET Core
在ASP.NET Core中实现DropdownList组件
The DropdownList is a single-selection control that displays a list of predefined values. Users can select one value from the dropdown list. It supports data binding, filtering, grouping, custom templates, and accessibility features.
DropdownList是一款单选控件,会显示预定义值的列表。用户可从下拉列表中选择一个值。它支持数据绑定、筛选、分组、自定义模板及无障碍功能。
When to Use This Skill
何时使用此技能
Use this skill when you need to:
- Create a single-selection dropdown in an ASP.NET Core application
- Bind dropdown data from server-side sources (array, database, API)
- Enable filtering for large lists
- Group related items
- Customize item appearance with templates
- Ensure accessibility compliance
- Cascade dropdowns based on parent selection
- Handle user selections with events
当你需要以下功能时使用此技能:
- 在ASP.NET Core应用中创建单选下拉框
- 从服务器端数据源(数组、数据库、API)绑定下拉框数据
- 为大型列表启用筛选功能
- 对相关项进行分组
- 使用模板自定义项的外观
- 确保符合无障碍标准
- 根据父级选择实现级联下拉框
- 通过事件处理用户选择
Component Overview
组件概述
Key Features:
- Data binding from local arrays and remote sources
- Real-time filtering with searchbox
- Automatic grouping of items
- Customizable item and value templates
- WCAG accessibility support with keyboard navigation
- Cascading dropdown support
- Virtual scrolling for large datasets
Common Properties:
- - Data array or DataManager
DataSource - - Field mapping (text, value, groupBy, iconCss)
Fields - - Enable/disable filtering
AllowFiltering - - Filtering algorithm (StartsWith, Contains, EndsWith)
FilterType - - Field name for grouping
GroupBy - - Custom item rendering
ItemTemplate - - Custom selected value rendering
ValueTemplate - - Hint text
Placeholder - - Selected value
Value - - Read-only state
ReadOnly
核心特性:
- 支持从本地数组和远程数据源绑定数据
- 带搜索框的实时筛选
- 自动对项进行分组
- 可自定义的项模板和值模板
- 支持WCAG无障碍标准及键盘导航
- 级联下拉框支持
- 针对大型数据集的虚拟滚动
常用属性:
- - 数据数组或DataManager
DataSource - - 字段映射(text、value、groupBy、iconCss)
Fields - - 启用/禁用筛选
AllowFiltering - - 筛选算法(StartsWith、Contains、EndsWith)
FilterType - - 用于分组的字段名
GroupBy - - 自定义项渲染
ItemTemplate - - 自定义选中值渲染
ValueTemplate - - 提示文本
Placeholder - - 选中值
Value - - 只读状态
ReadOnly
Documentation and Navigation Guide
文档与导航指南
Getting Started
快速入门
📄 Read: references/getting-started.md
- Installation and NuGet package setup
- TagHelper registration and configuration
- Basic DropdownList implementation
- HTML structure and minimal examples
- CSS theme imports
- Click and change event handlers
📄 阅读: references/getting-started.md
- 安装及NuGet包配置
- TagHelper注册与配置
- 基础DropdownList实现
- HTML结构与最简示例
- CSS主题导入
- 点击和变更事件处理
Data Binding and Sources
数据绑定与数据源
📄 Read: references/data-binding.md
- Binding array of simple data (strings, numbers)
- Binding complex JSON objects
- Nested data structure mapping
- Remote data binding with DataManager
- OData and Web API integration
- Field mapping and value binding
- Understanding text and value fields
📄 阅读: references/data-binding.md
- 绑定简单数据数组(字符串、数字)
- 绑定复杂JSON对象
- 嵌套数据结构映射
- 使用DataManager绑定远程数据
- OData与Web API集成
- 字段映射与值绑定
- 理解文本字段与值字段
Filtering and Grouping
筛选与分组
📄 Read: references/filtering-grouping.md
- Enable and configure filtering
- Filter types (StartsWith, Contains, EndsWith)
- Case-insensitive filtering
- Grouping items by category
- Custom group headers
- Sort order configuration (ascending/descending)
- Virtual grouping for performance
📄 阅读: references/filtering-grouping.md
- 启用并配置筛选功能
- 筛选类型(StartsWith、Contains、EndsWith)
- 不区分大小写的筛选
- 按类别分组项
- 自定义分组标题
- 排序顺序配置(升序/降序)
- 用于性能优化的虚拟分组
Templates and Styling
模板与样式
📄 Read: references/templates-styling.md
- Item template customization
- Selected value template
- Header and footer templates
- Group header templates
- CSS class customization
- Theme styling and color schemes
- Responsive sizing and positioning
📄 阅读: references/templates-styling.md
- 项模板自定义
- 选中值模板
- 页眉与页脚模板
- 分组标题模板
- CSS类自定义
- 主题样式与配色方案
- 响应式尺寸与定位
Accessibility and Features
无障碍功能
📄 Read: references/accessibility-features.md
- WCAG 2.1 Level AA compliance
- Keyboard navigation (arrow keys, Enter, Tab)
- ARIA attributes and screen reader support
- Focus management and focus indicators
- Disabled state handling
- RTL (Right-to-Left) language support
- Tooltip and help text integration
📄 阅读: references/accessibility-features.md
- 符合WCAG 2.1 Level AA标准
- 键盘导航(方向键、Enter、Tab)
- ARIA属性与屏幕阅读器支持
- 焦点管理与焦点指示器
- 禁用状态处理
- RTL(从右到左)语言支持
- 工具提示与帮助文本集成
Advanced Scenarios
高级场景
📄 Read: references/advanced-scenarios.md
- Cascading dropdowns (dependent selection)
- Multi-select dropdown patterns
- Virtual scrolling for large datasets
- Search and autocomplete patterns
- API integration and async data loading
- Error handling and empty state
- Performance optimization tips
📄 阅读: references/advanced-scenarios.md
- 级联下拉框(依赖选择)
- 多选下拉框模式
- 针对大型数据集的虚拟滚动
- 搜索与自动完成模式
- API集成与异步数据加载
- 错误处理与空状态
- 性能优化技巧
Quick Start Example
快速入门示例
Controller (HomeController.cs):
csharp
public class HomeController : Controller
{
public IActionResult Index()
{
ViewBag.Fruits = new List<string> { "Apple", "Orange", "Banana", "Mango" };
return View();
}
}View (Index.cshtml):
csharp
@Html.EJ2().DropDownList()
.Id("DropdownList")
.DataSource(ViewBag.Fruits)
.Placeholder("Select fruit")
.Render()控制器(HomeController.cs):
csharp
public class HomeController : Controller
{
public IActionResult Index()
{
ViewBag.Fruits = new List<string> { "Apple", "Orange", "Banana", "Mango" };
return View();
}
}视图(Index.cshtml):
csharp
@Html.EJ2().DropDownList()
.Id("DropdownList")
.DataSource(ViewBag.Fruits)
.Placeholder("Select fruit")
.Render()Common Patterns
常见模式
Pattern 1: Basic Selection with Event Handling
模式1:带事件处理的基础选择
Model:
csharp
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}Controller:
csharp
public IActionResult Index()
{
var categories = new List<Category>
{
new Category { Id = 1, Name = "Electronics" },
new Category { Id = 2, Name = "Furniture" },
new Category { Id = 3, Name = "Clothing" }
};
ViewBag.Categories = categories;
return View();
}View:
csharp
@Html.EJ2().DropDownList()
.Id("Category")
.DataSource(ViewBag.Categories)
.Fields(fields => fields.Text("Name").Value("Id"))
.Change("onCategoryChange")
.Placeholder("Select category")
.Render()
<script>
function onCategoryChange(args) {
console.log('Selected ID:', args.value);
console.log('Selected Text:', args.text);
// Perform action based on selection
}
</script>模型:
csharp
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}控制器:
csharp
public IActionResult Index()
{
var categories = new List<Category>
{
new Category { Id = 1, Name = "Electronics" },
new Category { Id = 2, Name = "Furniture" },
new Category { Id = 3, Name = "Clothing" }
};
ViewBag.Categories = categories;
return View();
}视图:
csharp
@Html.EJ2().DropDownList()
.Id("Category")
.DataSource(ViewBag.Categories)
.Fields(fields => fields.Text("Name").Value("Id"))
.Change("onCategoryChange")
.Placeholder("Select category")
.Render()
<script>
function onCategoryChange(args) {
console.log('Selected ID:', args.value);
console.log('Selected Text:', args.text);
// Perform action based on selection
}
</script>Pattern 2: Cascading Dropdowns
模式2:级联下拉框
Models:
csharp
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public int CountryId { get; set; }
}Controller:
csharp
public IActionResult Index()
{
var countries = new List<Country>
{
new Country { Id = 1, Name = "USA" },
new Country { Id = 2, Name = "Canada" },
new Country { Id = 3, Name = "Mexico" }
};
ViewBag.Countries = countries;
return View();
}
[HttpGet("api/cities/{countryId}")]
public IActionResult GetCities(int countryId)
{
var cities = new List<City>
{
new City { Id = 1, Name = "New York", CountryId = 1 },
new City { Id = 2, Name = "Los Angeles", CountryId = 1 },
new City { Id = 3, Name = "Toronto", CountryId = 2 },
new City { Id = 4, Name = "Vancouver", CountryId = 2 }
};
var filtered = cities.Where(c => c.CountryId == countryId)
.Select(c => new { c.Id, c.Name })
.ToList();
return Json(filtered);
}View:
csharp
<!-- First dropdown -->
@Html.EJ2().DropDownList()
.Id("Country")
.DataSource(ViewBag.Countries)
.Fields(fields => fields.Text("Name").Value("Id"))
.Change("onCountryChange")
.Placeholder("Select country")
.Render()
<!-- Second dropdown (dependent) -->
@Html.EJ2().DropDownList()
.Id("City")
.Placeholder("Select city")
.Render()
<script>
function onCountryChange(args) {
var cityDropdown = document.getElementById('City').ej2_instances[0];
if (args.value) {
// Fetch cities for selected country
fetch('/home/GetCities/' + args.value)
.then(response => response.json())
.then(data => {
cityDropdown.dataSource = data;
cityDropdown.value = null;
})
.catch(error => console.error('Error:', error));
} else {
cityDropdown.dataSource = [];
}
}
</script>模型:
csharp
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public int CountryId { get; set; }
}控制器:
csharp
public IActionResult Index()
{
var countries = new List<Country>
{
new Country { Id = 1, Name = "USA" },
new Country { Id = 2, Name = "Canada" },
new Country { Id = 3, Name = "Mexico" }
};
ViewBag.Countries = countries;
return View();
}
[HttpGet("api/cities/{countryId}")]
public IActionResult GetCities(int countryId)
{
var cities = new List<City>
{
new City { Id = 1, Name = "New York", CountryId = 1 },
new City { Id = 2, Name = "Los Angeles", CountryId = 1 },
new City { Id = 3, Name = "Toronto", CountryId = 2 },
new City { Id = 4, Name = "Vancouver", CountryId = 2 }
};
var filtered = cities.Where(c => c.CountryId == countryId)
.Select(c => new { c.Id, c.Name })
.ToList();
return Json(filtered);
}视图:
csharp
<!-- First dropdown -->
@Html.EJ2().DropDownList()
.Id("Country")
.DataSource(ViewBag.Countries)
.Fields(fields => fields.Text("Name").Value("Id"))
.Change("onCountryChange")
.Placeholder("Select country")
.Render()
<!-- Second dropdown (dependent) -->
@Html.EJ2().DropDownList()
.Id("City")
.Placeholder("Select city")
.Render()
<script>
function onCountryChange(args) {
var cityDropdown = document.getElementById('City').ej2_instances[0];
if (args.value) {
// Fetch cities for selected country
fetch('/home/GetCities/' + args.value)
.then(response => response.json())
.then(data => {
cityDropdown.dataSource = data;
cityDropdown.value = null;
})
.catch(error => console.error('Error:', error));
} else {
cityDropdown.dataSource = [];
}
}
</script>Pattern 3: Filtered List with Remote Data
模式3:带远程数据的筛选列表
Model:
csharp
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}API Controller:
csharp
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
var products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99m },
new Product { Id = 2, Name = "Mouse", Price = 25.50m },
new Product { Id = 3, Name = "Keyboard", Price = 75.00m },
new Product { Id = 4, Name = "Monitor", Price = 299.99m }
};
return Ok(products);
}
}View:
csharp
@Html.EJ2().DropDownList()
.Id("Products")
.DataSource(d => d.Url("/api/products"))
.Fields(fields => fields.Text("Name").Value("Id"))
.AllowFiltering(true)
.FilterType(FilterType.Contains)
.Placeholder("Search products...")
.Render()模型:
csharp
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}API控制器:
csharp
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
var products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99m },
new Product { Id = 2, Name = "Mouse", Price = 25.50m },
new Product { Id = 3, Name = "Keyboard", Price = 75.00m },
new Product { Id = 4, Name = "Monitor", Price = 299.99m }
};
return Ok(products);
}
}视图:
csharp
@Html.EJ2().DropDownList()
.Id("Products")
.DataSource(d => d.Url("/api/products"))
.Fields(fields => fields.Text("Name").Value("Id"))
.AllowFiltering(true)
.FilterType(FilterType.Contains)
.Placeholder("Search products...")
.Render()Key Props and When to Use
关键属性及适用场景
| Property | Type | When to Use |
|---|---|---|
| Array/DataManager | Always required for populating items |
| FieldSettings | When binding complex data objects |
| string/number | When pre-selecting an item |
| bool | For lists with 10+ items |
| FilterType | Customize search behavior |
| string | When items have logical categories |
| string | For rich item content |
| string | For better UX guidance |
| bool | When preventing user changes |
| bool | For conditional enabling |
| 属性 | 类型 | 适用场景 |
|---|---|---|
| Array/DataManager | 始终需要用于填充项 |
| FieldSettings | 绑定复杂数据对象时 |
| string/number | 需要预选中项时 |
| bool | 列表项数量≥10个时 |
| FilterType | 自定义搜索行为时 |
| string | 项具有逻辑分类时 |
| string | 需要富文本项内容时 |
| string | 需要更好的用户引导时 |
| bool | 需要阻止用户修改时 |
| bool | 需要条件启用时 |
Common Use Cases
常见使用场景
1. Form Selection Field
1. 表单选择字段
Dropdown in a form for selecting category, status, or type
表单中的下拉框,用于选择类别、状态或类型
2. Cascading Selection
2. 级联选择
Multiple dropdowns where child depends on parent selection
多个下拉框,子下拉框依赖父下拉框的选择
3. Searchable List
3. 可搜索列表
Enable filtering for dropdown with large number of items
为包含大量项的下拉框启用筛选功能
4. Grouped Items
4. 分组项
Organize items by category (e.g., Product Category > Subcategory)
按类别组织项(例如:产品类别 > 子类别)
5. Dynamic Data
5. 动态数据
Load items from API or database based on user actions
根据用户操作从API或数据库加载项
6. Template Customization
6. 模板自定义
Display rich content with icons, images, or badges in dropdown items
在下拉项中显示图标、图片或徽章等富内容
Next Steps
下一步操作
- Just starting? Read Getting Started
- Binding server data? Read Data Binding
- Need filtering? Read Filtering and Grouping
- Customizing appearance? Read Templates and Styling
- Need accessibility? Read Accessibility and Features
- Advanced scenarios? Read Advanced Scenarios
For the parent library overview and other components, see Implementing Syncfusion ASP.NET Core Components.
- 刚入门? 阅读快速入门
- 绑定服务器数据? 阅读数据绑定
- 需要筛选功能? 阅读筛选与分组
- 自定义外观? 阅读模板与样式
- 需要无障碍支持? 阅读无障碍功能
- 高级场景? 阅读高级场景
如需了解父级库概述及其他组件,请查看实现Syncfusion ASP.NET Core组件。