如何将MudBlazor颜色选择器绑定到Blazor Server模型?
Blazor Server中MudBlazor颜色选择器绑定与必填验证修复方案
问题根源
原代码存在三个核心问题:
- 颜色选择器未直接绑定到模型的
colour字段,而是使用独立的_pickerColor变量,导致选中颜色无法同步到模型 - 未给颜色选择器添加
For属性,无法触发基于数据注解的必填验证 - 模型中
colour字段的[StringLength]提示存在拼写错误("Coloir"应为"Color")
修复步骤
- 直接绑定到模型字段:将MudColorPicker的
@bind-Value直接关联到model.colour,MudBlazor会自动处理MudColor与string类型的适配 - 添加验证关联:增加
For="@(() => model.colour)"属性,让DataAnnotationsValidator识别必填规则 - 清理冗余代码:移除独立的
_pickerColor变量和UpdateSelectedColor方法,简化逻辑 - 修正拼写错误:修正模型中[StringLength]的错误提示文本
完整修复代码
@using System.ComponentModel.DataAnnotations @using MudBlazor.Utilities <EditForm Model="@model" OnValidSubmit="OnValidSubmit"> <DataAnnotationsValidator/> <MudGrid> <MudItem xs="12" sm="7"> <MudCard> <MudCardContent> <MudTextField Label="Category Name" HelperText="Max. 20 characters" @bind-Value="model.Name" For="@(() => model.Name)"/> <MudItem xs="12" md="6" lg="4"> <MudPaper Class="d-flex"> <MudColorPicker Rounded="true" @bind-Value="model.colour" For="@(() => model.colour)" Label="Category Colour*" Placeholder="Select Color" ColorPickerView="ColorPickerView.Grid" DisableAlpha="true" DisableColorField="false" DisablePreview="false" DisableModeSwitch="true" DisableSliders="true" ColorPickerMode="ColorPickerMode.HEX" /> </MudPaper> </MudItem> </MudCardContent> <MudCardActions> <MudButton ButtonType="ButtonType.Submit" Variant="Variant.Filled" Color="Color.Primary" Class="ml-auto">Register</MudButton> </MudCardActions> </MudCard> </MudItem> <MudItem xs="12" sm="5"> <MudPaper Class="pa-4 mud-height-full"> <MudText Typo="Typo.subtitle2">Validation Summary</MudText> @if (success) { <MudText Color="Color.Success">Success</MudText> } else { <MudText Color="@Color.Error"> <ValidationSummary /> </MudText> } </MudPaper> </MudItem> <MudItem xs="12"> <MudText Typo="Typo.body2" Align="Align.Center"> Fill out the form correctly to see the success message. </MudText> </MudItem> </MudGrid> </EditForm> @code { Category model = new Category(); bool success; public class Category { [Required] [StringLength(20, ErrorMessage = "Name length can't be more than 20")] public string Name { get; set; } [Required(ErrorMessage = "Colour is required")] [StringLength(20, ErrorMessage = "Color length can't be more than 20")] public string colour { get; set; } } private void OnValidSubmit(EditContext context) { success = true; // 此时model.colour已存储选中的HEX颜色值,可在此处理业务逻辑 StateHasChanged(); } }
关键说明
- MudBlazor的
MudColorPicker会自动将选中的颜色转换为HEX格式字符串,直接绑定到string类型的模型字段即可生效 - 添加
For属性后,未选择颜色时表单提交会触发Required验证错误,错误信息会显示在ValidationSummary中 - 提交成功后,
model.colour的值为选中颜色的标准HEX格式(例如#FF0000),可直接用于后续业务处理
内容的提问来源于stack exchange,提问作者Lisa
相关产品推荐
相关产品推荐

