ModelState对于可为空的属性无效 [英] ModelState is invalid for a nullable property

查看:86
本文介绍了ModelState对于可为空的属性无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,其中公司ID属性允许空值

I have a model where the property CompanyID allows a null value

public partial class ReportTemplateItem
{
    [Key]
    public int ReportTemplateItemID { get; set; }

    [Required]
    public int ReportTemplateID { get; set; }
    
    public int? CompanyID { get; set; }
}

在DBContext OnModelCreating中,没有为CompanyID声明任何属性

In the DBContext OnModelCreating, there is no property declared for CompanyID

但是在发布时,ModelState无效.如果我删除ModelState验证,该表单将按预期工作

But when posting the ModelState is Invalid. The form works as intended if I remove ModelState validation

ModelState无效

接受空值似乎是模型验证的默认行为,我缺少什么?

Accepting a null value appears to be the default behavior for Model Validation, what am i missing?

具有EF Core 3.0的剃刀页面,可空引用类型已禁用

Razor Pages with EF Core 3.0, Nullable Reference Types is disabled

非常感谢

编辑-验证时无效的对象

推荐答案

如果有帮助,您可以尝试根本不发送空值(将其从正在发送的数据中排除).

If this is any help, you may try just not to send a null value at all (exclude it from data being sent).

例如,不发送以下json数据:

For example, instead of sending the folowing json data:

    var data = {
        reportTemplateItemID: 1,
        reportTemplateID: 2,
        companyID: null
    };

仅发送:

    var data = {
        reportTemplateItemID: 1,
        reportTemplateID: 2
    };

如果您有一个复杂的对象,则可以在进行ajax调用之前轻松剥离所有null:

If you have a complex object, you may easily strip all nulls before making an ajax call:

// let's remove null and undefined values
// an easy way is to serialize using a replacer function and deserialize back
const str = JSON.stringify(data, function(key, value) { return value === null ? undefined : value; });
const newData = JSON.parse(str);

查看其工作原理:

var data = { "aaa" : undefined, "bbb": null, ccc : ""}
// newData = "{"ccc":""}"

至少在ASP.NET Core 3.1中,ModelState验证不会失败(只要值类型可以为空),至少在ASP.NET Core 3.1中(我没有检查其他版本).

ModelState validation won't fail in such case (as long as the value type is nullable), at least in ASP.NET Core 3.1 (I didn't check other versions).

这篇关于ModelState对于可为空的属性无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆