Blazor中为NULL表单项编写IF ELSE语句实现提交校验的咨询
表单提交非空校验失效修复方案
问题原因
你当前的代码仅判断了AssigneeDto对象本身是否为空,没有触发EditContext内置的字段校验逻辑,也没有对Dto内部的字段做非空判断,因此只要Dto实例存在,无论内部字段是否为空都会走数据库插入逻辑。
修复步骤
第一步:给Dto字段加数据注解校验
在AssigneeDto类的所有必填字段上添加[Required]注解,示例如下:
using System.ComponentModel.DataAnnotations; public class AssigneeDto { [Required(ErrorMessage = "负责人姓名不能为空")] public string Name { get; set; } [Required(ErrorMessage = "联系电话不能为空")] public string Phone { get; set; } // 其他必填字段同样添加[Required]注解即可 }
第二步:修改提交处理方法
在处理提交逻辑前先调用EditContext.Validate()触发全局校验,校验通过后再执行插入操作,还可以额外加一层手动校验做兜底,修改后代码如下:
private async Task OnSubmitHandler(EditContext editContext) { // 触发所有字段的注解校验,校验不通过直接返回报错 if (!editContext.Validate()) { NotificationReference.Show(new NotificationModel() { ThemeColor = ThemeColors.Error, Text = "请填写所有必填字段后再提交", }); return; } AssigneeDto assigneeDto = editContext.Model as AssigneeDto; if (assigneeDto != null) { // 兜底手动校验,避免注解漏加导致的空值提交 if (string.IsNullOrWhiteSpace(assigneeDto.Name) || string.IsNullOrWhiteSpace(assigneeDto.Phone) /* 其他必填字段同理添加判断 */) { NotificationReference.Show(new NotificationModel() { ThemeColor = ThemeColors.Error, Text = "存在空的必填字段,提交失败", }); return; } await _assigneeClient.CreateAssignee(sm.id, assigneeDto); NotificationReference.Show(new NotificationModel() { ThemeColor = ThemeColors.Success, Text = "记录添加成功!", }); FormData = new AssigneeDto(); CurrentForm = new EditContext(FormData); CurrentForm.AddDataAnnotationsValidation(); } else { NotificationReference.Show(new NotificationModel() { ThemeColor = ThemeColors.Error, Text = "记录添加失败!", }); } }
补充说明
EditContext.Validate()会自动扫描所有加了数据注解的字段做校验,返回false即代表存在校验不通过的字段- 手动校验的兜底逻辑可以根据业务需求选择是否保留,能有效避免注解漏加、校验规则异常等特殊场景的空值提交问题
内容的提问来源于stack exchange,提问作者Brandon
相关产品推荐
相关产品推荐

