syncfusion-blazor-dataform
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseImplementing Syncfusion Blazor DataForm Component
实现Syncfusion Blazor DataForm组件
A comprehensive skill for implementing the Syncfusion Blazor DataForm component. This skill covers installation, configuration, data binding, validation, event handling, templating, and customization of forms in Blazor applications.
本技能全面讲解如何实现Syncfusion Blazor DataForm组件,涵盖Blazor应用中表单的安装、配置、数据绑定、验证、事件处理、模板化和自定义等内容。
Component Overview
组件概述
The Syncfusion Blazor DataForm (SfDataForm) is a powerful form component that streamlines the creation of dynamic, data-driven forms with automatic validation, field binding, and event handling. It supports:
- Automatic field generation from model properties
- Built-in validation with data annotations and custom rules
- Multiple binding approaches (model, EditContext)
- Customizable layouts with columns, grouping, and sections
- Template-based rendering for custom field designs
- Event-driven architecture for form and field-level reactions
- Localization support for validation messages and UI text
- Accessible form rendering with proper labels and ARIA attributes
Syncfusion Blazor DataForm(SfDataForm)是一款功能强大的表单组件,可简化动态数据驱动表单的创建,具备自动验证、字段绑定和事件处理功能。它支持:
- 自动字段生成:从模型属性自动生成字段
- 内置验证:支持数据注解和自定义规则
- 多种绑定方式(模型绑定、EditContext绑定)
- 可自定义布局:支持列、分组和分段
- 基于模板的渲染:用于自定义字段设计
- 事件驱动架构:支持表单和字段级别的响应
- 本地化支持:验证消息和UI文本可本地化
- 无障碍表单渲染:包含合适的标签和ARIA属性
Documentation and Navigation Guide
文档与导航指南
Getting Started
快速入门
📄 Read: references/getting-started.md
Start here for installation, NuGet package setup, namespace imports, service registration, theme configuration, and a basic DataForm example.
- Installation & NuGet packages
- Blazor project setup (Server/WebAssembly/Web App)
- Namespace imports & service registration
- Theme setup & configuration
- Basic DataForm creation
- Running your first form
📄 阅读: references/getting-started.md
从这里开始学习安装、NuGet包设置、命名空间导入、服务注册、主题配置以及基础DataForm示例。
- 安装与NuGet包
- Blazor项目设置(Server/WebAssembly/Web App)
- 命名空间导入与服务注册
- 主题设置与配置
- 创建基础DataForm
- 运行首个表单
Form Items and Field Configuration
表单项与字段配置
📄 Read: references/form-items.md
Learn how to define form items, configure labels, placeholders, hints, editor types, and customize individual field behavior.
- FormItem element configuration
- Label, placeholder configurations
- Editor type selection
- Disabling and hiding fields
- Custom attributes (required, pattern, data annotations)
- Form grouping and column organization
📄 阅读: references/form-items.md
学习如何定义表单项、配置标签、占位符、提示、编辑器类型,以及自定义单个字段的行为。
- FormItem元素配置
- 标签、占位符配置
- 编辑器类型选择
- 禁用和隐藏字段
- 自定义属性(必填、正则、数据注解)
- 表单分组与列组织
Auto-Generation of Form Fields
表单字段自动生成
📄 Read: references/autogeneration.md
Discover how to automatically generate form fields from model properties using FormAutoGenerateItems, including type mapping and combining auto-generated with custom fields.
- FormAutoGenerateItems overview
- Type-to-component mapping (int, string, DateTime, bool, enum, etc.)
- Auto-generating fields for primitive types
- Combining auto-generated and custom fields
- Canceling auto-generation for specific fields
- Configuration options
📄 阅读: references/autogeneration.md
了解如何使用FormAutoGenerateItems从模型属性自动生成表单字段,包括类型映射以及结合自动生成字段和自定义字段。
- FormAutoGenerateItems概述
- 类型到组件的映射(int、string、DateTime、bool、枚举等)
- 为基本类型自动生成字段
- 结合自动生成字段和自定义字段
- 取消特定字段的自动生成
- 配置选项
Data Binding
数据绑定
📄 Read: references/data-binding.md
Understand model binding, EditContext binding, two-way data binding, and binding to complex data structures.
- Model binding basics
- EditContext binding approach
- Form-level and field-level binding
- Two-way binding with nested objects
- Binding to complex models
- Data initialization and default values
- Form name and ID configuration
📄 阅读: references/data-binding.md
了解模型绑定、EditContext绑定、双向数据绑定以及绑定到复杂数据结构。
- 模型绑定基础
- EditContext绑定方式
- 表单级和字段级绑定
- 嵌套对象的双向绑定
- 绑定到复杂模型
- 数据初始化与默认值
- 表单名称和ID配置
Form Validation
表单验证
📄 Read: references/validation.md
Master form validation with data annotations, custom validation rules, Fluent Validation integration, and error message display.
- Data annotation validation (Required, Range, EmailAddress, etc.)
- DataAnnotationsValidator setup
- Custom validation attributes and rules
- Fluent Validation framework integration
- Complex model validation scenarios
- Displaying validation messages
- IsValid() method and validation state
- Conditional validation
📄 阅读: references/validation.md
掌握使用数据注解、自定义验证规则、Fluent Validation集成以及错误消息显示的表单验证方法。
- 数据注解验证(Required、Range、EmailAddress等)
- DataAnnotationsValidator设置
- 自定义验证属性和规则
- Fluent Validation框架集成
- 复杂模型验证场景
- 验证消息显示
- IsValid()方法与验证状态
- 条件验证
Form and Field Events
表单与字段事件
📄 Read: references/events.md
Learn about form submission events and field-level events for handling user interactions and form state changes.
- OnSubmit event (fires on every submit attempt)
- OnValidSubmit event (fires only on valid submission)
- OnInvalidSubmit event (fires only on validation failure)
- OnUpdate event (fires on field value changes)
- Event arguments and EditContext access
- Asynchronous event handlers
- Common event patterns
📄 阅读: references/events.md
学习表单提交事件和字段级事件,用于处理用户交互和表单状态变化。
- OnSubmit事件(每次提交尝试时触发)
- OnValidSubmit事件(仅在提交数据有效时触发)
- OnInvalidSubmit事件(仅在验证失败时触发)
- OnUpdate事件(字段值变化时触发)
- 事件参数与EditContext访问
- 异步事件处理程序
- 常见事件模式
Layout Customization
布局自定义
📄 Read: references/layout-customization.md
Customize form layout with columns, column spans, label positioning, floating labels, and custom button placement.
- Column layout configuration
- Column span and row span
- Columns count and responsiveness
- Label positioning (top, left, floating)
- Floating label styling
- Button alignment and positioning
- Custom submit/reset buttons
- Form grouping with FormGroup
📄 阅读: references/layout-customization.md
通过列、列跨度、标签定位、浮动标签和自定义按钮位置来自定义表单布局。
- 列布局配置
- 列跨度和行跨度
- 列数与响应式设计
- 标签定位(顶部、左侧、浮动)
- 浮动标签样式
- 按钮对齐与定位
- 自定义提交/重置按钮
- 使用FormGroup进行表单分组
Templates and Custom Rendering
模板与自定义渲染
📄 Read: references/templates.md
Create custom form layouts and field renderings using FormTemplate and FormItemTemplate with render fragments.
- FormTemplate for overall form layout customization
- FormItemTemplate for individual field rendering
- Template context and variables
- Custom editor rendering
- Render fragments and composition
- Advanced template patterns
- Template reusability
📄 阅读: references/templates.md
使用FormTemplate和FormItemTemplate结合渲染片段创建自定义表单布局和字段渲染效果。
- FormTemplate:用于整体表单布局自定义
- FormItemTemplate:用于单个字段渲染
- 模板上下文与变量
- 自定义编辑器渲染
- 渲染片段与组合
- 高级模板模式
- 模板复用
Localization
本地化
📄 Read: references/localization.md
Set up localization for validation messages, form labels, and error messages in multiple languages.
- Built-in localization resources
- Localizing error messages
- Custom localization setup
- Culture and language configuration
- RTL (right-to-left) support
📄 阅读: references/localization.md
设置验证消息、表单标签和错误消息的多语言本地化。
- 内置本地化资源
- 错误消息本地化
- 自定义本地化设置
- 区域和语言配置
- RTL(从右到左)支持
Quick Start Example
快速入门示例
Here's a minimal working example to get started:
razor
@page "/dataform-example"
@using System.ComponentModel.DataAnnotations
@using Syncfusion.Blazor.DataForm
<SfDataForm ID="MyDataForm"
Model="@employeeModel">
<FormValidator>
<DataAnnotationsValidator></DataAnnotationsValidator>
</FormValidator>
<FormItems>
<FormAutoGenerateItems></FormAutoGenerateItems>
</FormItems>
</SfDataForm>
@code {
public class EmployeeModel
{
[Required(ErrorMessage = "First Name is required")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Invalid email address")]
[Display(Name = "Email")]
public string Email { get; set; }
[Range(18, 65, ErrorMessage = "Age must be between 18 and 65")]
[Display(Name = "Age")]
public int Age { get; set; }
[Display(Name = "Date of Birth")]
public DateTime? DateOfBirth { get; set; }
}
private EmployeeModel employeeModel = new EmployeeModel();
}以下是一个最小可用示例,帮助你快速上手:
razor
@page "/dataform-example"
@using System.ComponentModel.DataAnnotations
@using Syncfusion.Blazor.DataForm
<SfDataForm ID="MyDataForm"
Model="@employeeModel">
<FormValidator>
<DataAnnotationsValidator></DataAnnotationsValidator>
</FormValidator>
<FormItems>
<FormAutoGenerateItems></FormAutoGenerateItems>
</FormItems>
</SfDataForm>
@code {
public class EmployeeModel
{
[Required(ErrorMessage = "First Name is required")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Invalid email address")]
[Display(Name = "Email")]
public string Email { get; set; }
[Range(18, 65, ErrorMessage = "Age must be between 18 and 65")]
[Display(Name = "Age")]
public int Age { get; set; }
[Display(Name = "Date of Birth")]
public DateTime? DateOfBirth { get; set; }
}
private EmployeeModel employeeModel = new EmployeeModel();
}Common Patterns
常见模式
Pattern 1: Form with Validation and Submission
模式1:带验证和提交的表单
razor
<SfDataForm ID="ContactForm" Model="@contact" OnValidSubmit="HandleValidSubmit">
<FormValidator>
<DataAnnotationsValidator></DataAnnotationsValidator>
</FormValidator>
<FormItems>
<FormItem Field="@nameof(contact.Name)" LabelText="Full Name"></FormItem>
<FormItem Field="@nameof(contact.Email)" LabelText="Email Address"></FormItem>
<FormItem Field="@nameof(contact.Message)" EditorType="FormEditorType.TextArea"></FormItem>
</FormItems>
</SfDataForm>
@code {
private Contact contact = new();
private async Task HandleValidSubmit(EditContext context)
{
// Save contact to database
await SaveContactAsync(contact);
}
}razor
<SfDataForm ID="ContactForm" Model="@contact" OnValidSubmit="HandleValidSubmit">
<FormValidator>
<DataAnnotationsValidator></DataAnnotationsValidator>
</FormValidator>
<FormItems>
<FormItem Field="@nameof(contact.Name)" LabelText="Full Name"></FormItem>
<FormItem Field="@nameof(contact.Email)" LabelText="Email Address"></FormItem>
<FormItem Field="@nameof(contact.Message)" EditorType="FormEditorType.TextArea"></FormItem>
</FormItems>
</SfDataForm>
@code {
private Contact contact = new();
private async Task HandleValidSubmit(EditContext context)
{
// Save contact to database
await SaveContactAsync(contact);
}
}Pattern 2: Auto-Generated Form with Custom Fields
模式2:带自定义字段的自动生成表单
razor
<SfDataForm Model="@product">
<FormItems>
<FormItem Field="@nameof(product.Name)" LabelText="Product Name"></FormItem>
<FormAutoGenerateItems></FormAutoGenerateItems>
<FormItem Field="@nameof(product.Category)" EditorType="FormEditorType.DropDownList"></FormItem>
</FormItems>
</SfDataForm>
@code {
private Product product = new();
}razor
<SfDataForm Model="@product">
<FormItems>
<FormItem Field="@nameof(product.Name)" LabelText="Product Name"></FormItem>
<FormAutoGenerateItems></FormAutoGenerateItems>
<FormItem Field="@nameof(product.Category)" EditorType="FormEditorType.DropDownList"></FormItem>
</FormItems>
</SfDataForm>
@code {
private Product product = new();
}Pattern 3: Form with Cascading Fields
模式3:级联字段表单
razor
<SfDataForm Model="@order" OnUpdate="HandleFieldUpdate">
<FormItems>
<FormItem Field="@nameof(order.Country)" LabelText="Country"></FormItem>
<FormItem Field="@nameof(order.City)" LabelText="City"></FormItem>
<FormAutoGenerateItems></FormAutoGenerateItems>
</FormItems>
</SfDataForm>
@code {
private Order order = new();
private async Task HandleFieldUpdate(FormUpdateEventArgs args)
{
if (args.FieldName == nameof(Order.Country))
{
// Update cities based on selected country
order.City = await GetCitiesForCountryAsync(order.Country);
}
}
}razor
<SfDataForm Model="@order" OnUpdate="HandleFieldUpdate">
<FormItems>
<FormItem Field="@nameof(order.Country)" LabelText="Country"></FormItem>
<FormItem Field="@nameof(order.City)" LabelText="City"></FormItem>
<FormAutoGenerateItems></FormAutoGenerateItems>
</FormItems>
</SfDataForm>
@code {
private Order order = new();
private async Task HandleFieldUpdate(FormUpdateEventArgs args)
{
if (args.FieldName == nameof(Order.Country))
{
// Update cities based on selected country
order.City = await GetCitiesForCountryAsync(order.Country);
}
}
}Pattern 4: Custom Layout with Columns
模式4:带列的自定义布局
razor
<SfDataForm Model="@employee" ColumnCount="2">
<FormItems>
<FormItem Field="@nameof(employee.FirstName)" LabelText="First Name" ColumnSpan="1"></FormItem>
<FormItem Field="@nameof(employee.LastName)" LabelText="Last Name" ColumnSpan="1"></FormItem>
<FormItem Field="@nameof(employee.Email)" LabelText="Email" ColumnSpan="2"></FormItem>
<FormItem Field="@nameof(employee.Department)" LabelText="Department" ColumnSpan="1"></FormItem>
<FormItem Field="@nameof(employee.Salary)" LabelText="Salary" ColumnSpan="1"></FormItem>
</FormItems>
</SfDataForm>
@code {
private Employee employee = new();
}razor
<SfDataForm Model="@employee" ColumnCount="2">
<FormItems>
<FormItem Field="@nameof(employee.FirstName)" LabelText="First Name" ColumnSpan="1"></FormItem>
<FormItem Field="@nameof(employee.LastName)" LabelText="Last Name" ColumnSpan="1"></FormItem>
<FormItem Field="@nameof(employee.Email)" LabelText="Email" ColumnSpan="2"></FormItem>
<FormItem Field="@nameof(employee.Department)" LabelText="Department" ColumnSpan="1"></FormItem>
<FormItem Field="@nameof(employee.Salary)" LabelText="Salary" ColumnSpan="1"></FormItem>
</FormItems>
</SfDataForm>
@code {
private Employee employee = new();
}Key Properties and Methods
关键属性与方法
Common Properties
常见属性
| Property | Type | Purpose |
|---|---|---|
| object | The data model bound to the form |
| EditContext | Blazor EditContext for advanced binding scenarios |
| int | Number of columns for form layout |
| EventCallback | Fires when form is submitted with valid data |
| EventCallback | Fires when form is submitted with invalid data |
| EventCallback | Fires on every submit attempt |
| EventCallback | Fires when a field value changes |
| 属性 | 类型 | 用途 |
|---|---|---|
| object | 绑定到表单的数据模型 |
| EditContext | Blazor EditContext,用于高级绑定场景 |
| int | 表单布局的列数 |
| EventCallback | 表单提交数据有效时触发 |
| EventCallback | 表单提交数据无效时触发 |
| EventCallback | 每次提交尝试时触发 |
| EventCallback | 字段值变化时触发 |
Available FormEditorType Values
可用的FormEditorType值
Important: In most cases, you don't need to specify as the DataForm automatically selects the appropriate editor based on your model property type. Use these values only when you need to override the default behavior.
EditorType| FormEditorType | Use Case | When to Use |
|---|---|---|
| Single-line text input | Override for string fields (default), not needed for numeric types |
| Multi-line text input | When you need multi-line text entry for string properties |
| Date selection only | Override for DateTime (default for DateTime) |
| Date and time selection | When you need both date and time for DateTime properties |
| Time selection only | When you need only time selection for TimeSpan or DateTime |
| Dropdown selection from list | For enum or custom list selection |
| Editable dropdown with filtering | When you need searchable dropdown |
| Auto-complete with suggestions | When you need auto-suggest functionality |
| Boolean toggle (note: lowercase 'b') | Override for bool (default), NOT |
| Toggle switch for boolean | Alternative to checkbox for bool properties |
| Password input with masking | For password string fields |
Critical Notes:
- ⚠️ Automatic Type Mapping: The DataForm intelligently maps C# types to appropriate editors automatically:
- ,
int,long,decimal,double→ Numeric textbox (no EditorType needed)float - → Textbox (no EditorType needed)
string - → Checkbox (no EditorType needed)
bool - → DatePicker (no EditorType needed)
DateTime - → DropDownList (no EditorType needed)
enum
- ⚠️ Use (lowercase 'b'), NOT
Checkbox(capital B)CheckBox - ⚠️ There is NO editor type - numeric behavior is automatic based on property type
NumericTextBox - ⚠️ Only specify when you want to override the default behavior
EditorType
重要提示:大多数情况下,你无需指定,因为DataForm会根据模型属性类型自动选择合适的编辑器。仅当需要覆盖默认行为时才使用这些值。
EditorType| FormEditorType | 使用场景 | 使用时机 |
|---|---|---|
| 单行文本输入 | 覆盖字符串字段的默认编辑器(默认即为TextBox),数值类型无需使用 |
| 多行文本输入 | 当需要为字符串属性提供多行文本输入时 |
| 仅日期选择 | 覆盖DateTime类型的默认编辑器(DateTime默认即为DatePicker) |
| 日期和时间选择 | 当需要为DateTime属性同时选择日期和时间时 |
| 仅时间选择 | 当需要为TimeSpan或DateTime类型仅选择时间时 |
| 从列表中选择 | 用于枚举或自定义列表选择 |
| 可编辑的带筛选下拉框 | 当需要可搜索的下拉框时 |
| 带建议的自动补全 | 当需要自动提示功能时 |
| 布尔值切换(注意:小写'b') | 覆盖bool类型的默认编辑器(默认即为Checkbox),请勿使用 |
| 布尔值切换开关 | bool属性的复选框替代方案 |
| 带掩码的密码输入 | 用于密码类型的字符串字段 |
关键注意事项:
- ⚠️ 自动类型映射:DataForm会智能地将C#类型映射到合适的编辑器:
- 、
int、long、decimal、double→ 数值文本框(无需指定EditorType)float - → 文本框(无需指定EditorType)
string - → 复选框(无需指定EditorType)
bool - → 日期选择器(无需指定EditorType)
DateTime - → 下拉框(无需指定EditorType)
enum
- ⚠️ 使用(小写'b'),请勿使用
Checkbox(大写B)CheckBox - ⚠️ 不存在编辑器类型 - 数值行为会根据属性类型自动生效
NumericTextBox - ⚠️ 仅当需要覆盖默认行为时才指定
EditorType
Common Methods
常见方法
| Method | Purpose |
|---|---|
| Refresh form and re-render fields |
| Programmatically submit the form |
| Clear form and reset to initial values |
| Check if form is valid |
| Trigger validation without submitting |
| 方法 | 用途 |
|---|---|
| 刷新表单并重新渲染字段 |
| 以编程方式提交表单 |
| 清空表单并重置为初始值 |
| 检查表单是否有效 |
| 触发验证但不提交表单 |
Important EditorType Guidelines
重要的EditorType指南
When configuring FormItem elements with , keep these critical points in mind:
EditorType-
Automatic Editor Selection: The DataForm automatically selects the appropriate editor based on your model property type. You typically don't need to specifyunless you want to override the default behavior.
EditorType- Numeric properties (int, long, float, decimal, double) → Automatically render as numeric textbox
- String properties → Automatically render as textbox
- Boolean properties → Automatically render as checkbox
- DateTime properties → Automatically render as date picker
- Enum properties → Automatically render as dropdown
-
When to Specify EditorType: Only specifywhen you want to override the default:
EditorType- Use for multi-line string input
FormEditorType.TextArea - Use instead of checkbox for boolean
FormEditorType.Switch - Use instead of
FormEditorType.DateTimePickerfor DateTime with timeDatePicker - Use for password strings
FormEditorType.Password - Use or
FormEditorType.DropDownListfor custom listsComboBox
- Use
-
Checkbox Casing: When explicitly specifying checkbox, usewith lowercase 'b', not
FormEditorType.Checkbox.FormEditorType.CheckBox -
No NumericTextBox Type: There is no. Numeric behavior is automatic based on property type.
FormEditorType.NumericTextBox
Example:
razor
<!-- Numeric field - EditorType not needed, automatically renders numeric textbox -->
<FormItem Field="@nameof(model.Quantity)"
LabelText="Quantity">
</FormItem>
<!-- Boolean field - EditorType not needed, automatically renders checkbox -->
<FormItem Field="@nameof(model.IsActive)"
LabelText="Is Active">
</FormItem>
<!-- String field with TextArea override -->
<FormItem Field="@nameof(model.Description)"
LabelText="Description"
EditorType="FormEditorType.TextArea">
</FormItem>
<!-- Boolean field with Switch override -->
<FormItem Field="@nameof(model.IsEnabled)"
LabelText="Enabled"
EditorType="FormEditorType.Switch">
</FormItem>配置FormItem元素的时,请牢记以下关键点:
EditorType-
自动编辑器选择:DataForm会根据模型属性类型自动选择合适的编辑器。通常无需指定,除非你想覆盖默认行为。
EditorType- 数值属性(int、long、float、decimal、double)→ 自动渲染为数值文本框
- 字符串属性 → 自动渲染为文本框
- 布尔属性 → 自动渲染为复选框
- DateTime属性 → 自动渲染为日期选择器
- 枚举属性 → 自动渲染为下拉框
-
何时指定EditorType:仅当需要覆盖默认行为时才指定:
- 对多行字符串输入使用
FormEditorType.TextArea - 对布尔值使用替代复选框
FormEditorType.Switch - 对带时间的DateTime使用替代
FormEditorType.DateTimePickerDatePicker - 对密码字符串使用
FormEditorType.Password - 对自定义列表使用或
FormEditorType.DropDownListComboBox
- 对多行字符串输入使用
-
Checkbox大小写:当明确指定复选框时,使用(小写'b'),而非
FormEditorType.Checkbox。FormEditorType.CheckBox -
无NumericTextBox类型:不存在,数值行为会根据属性类型自动生效。
FormEditorType.NumericTextBox
示例:
razor
<!-- 数值字段 - 无需指定EditorType,自动渲染为数值文本框 -->
<FormItem Field="@nameof(model.Quantity)"
LabelText="Quantity">
</FormItem>
<!-- 布尔字段 - 无需指定EditorType,自动渲染为复选框 -->
<FormItem Field="@nameof(model.IsActive)"
LabelText="Is Active">
</FormItem>
<!-- 字符串字段,覆盖为TextArea -->
<FormItem Field="@nameof(model.Description)"
LabelText="Description"
EditorType="FormEditorType.TextArea">
</FormItem>
<!-- 布尔字段,覆盖为Switch -->
<FormItem Field="@nameof(model.IsEnabled)"
LabelText="Enabled"
EditorType="FormEditorType.Switch">
</FormItem>Related Skills
相关技能
- Syncfusion Blazor Components - Main library skill for all Blazor components
- AutoComplete - For dropdown field editors
- File Upload - For file input fields
- Syncfusion Blazor Components - 所有Blazor组件的主库技能
- AutoComplete - 用于下拉字段编辑器
- File Upload - 用于文件输入字段