ASP.NET Core中Ajax提交空值至可空字段报错的解决方法
问题解决思路
原因分析
虽然数据库中Explanation字段允许为空,但提交空值时报错,可能的原因包括:
- 目标API(
https://localhost:7198/api/Inventory)的接收DTO或实体对Explanation设置了必填校验(比如[Required]特性) - 当前项目的
CreateInventoryDto在模型绑定时,空字符串被框架默认校验逻辑判定为无效 - Ajax提交的空字符串在序列化后,被目标API的校验逻辑拒绝
解决方案
1. 明确CreateInventoryDto允许Explanation为空
当前CreateInventoryDto的Explanation是string类型(默认支持null),可显式添加[AllowNull]特性消除潜在的模型绑定校验问题:
public class CreateInventoryDto { public int InventoryID { get; set; } public int Brand { get; set; } public string Model { get; set; } public int Type { get; set; } public string SerialNo { get; set; } public int UsageCondition { get; set; } public int Condition { get; set; } public int Ownership { get; set; } public int CreateUser { get; set; } public DateTime CreateDate { get; set; } [AllowNull] public string Explanation { get; set; } }
2. 在FluentValidation中明确允许Explanation为空
无需添加NotEmpty规则,可按需添加长度限制规则,明确该字段支持空值:
public class InventoryAdditionValidator : AbstractValidator<CreateInventoryDto> { public InventoryAdditionValidator() { RuleFor(x => x.InventoryID).NotEmpty().WithMessage("Demirbaş No Boş Bırakılamaz"); RuleFor(x => x.Brand).NotEmpty().WithMessage("Marka Boş Bırakılamaz"); RuleFor(x => x.Model).NotEmpty().WithMessage("Model Boş Bırakılamaz"); RuleFor(x => x.Type).NotEmpty().WithMessage("Demirbaş Tipi Boş Bırakılamaz"); RuleFor(x => x.SerialNo).NotEmpty().WithMessage("Seri Numarası Boş Bırakılamaz"); RuleFor(x => x.UsageCondition).NotEmpty().WithMessage("Kullanım Durumu Boş Bırakılamaz"); RuleFor(x => x.Condition).NotEmpty().WithMessage("Demirbaş Durumu Boş Bırakılamaz"); RuleFor(x => x.Ownership).NotEmpty().WithMessage("Mülkiyet Durumu Boş Bırakılamaz"); // 可选:添加长度限制,不添加NotEmpty即允许空值 RuleFor(x => x.Explanation) .MaximumLength(500) .WithMessage("Açıklama en fazla 500 karakter olabilir"); } }
3. 处理Ajax提交的空值
当输入框为空时,将空字符串转为null,确保序列化后符合数据库的空值允许设置:
let value = { InventoryID: $("#input-qr-result").val(), Brand: $("#choices-single-brand").val(), Model: $("#txtModel").val(), Type: $("#choices-single-type").val(), SerialNo: $("#txtSerialNo").val(), UsageCondition: $("#choices-single-usage").val(), Condition: $("#choices-single-condition").val(), Ownership: $("#choices-single-ownership").val(), Explanation: $("#txtExplanation").val() || null }
4. 检查目标API的校验规则
报错核心大概率在接收请求的https://localhost:7198/api/Inventory接口中,需确认该接口的接收DTO/实体是否对Explanation设置了[Required]校验,若有则移除或替换为[AllowNull]:
// 目标API的接收DTO示例 public class InventoryReceiveDto { // 其他属性... [AllowNull] public string Explanation { get; set; } }
5. 排查全局校验配置
检查项目Program.cs/Startup.cs中是否有全局模型校验规则(比如强制所有字符串字段非空),确保没有影响Explanation字段的默认行为。
内容的提问来源于stack exchange,提问作者Gökmen Ada
相关产品推荐
相关产品推荐

