Search code examples
c#asp.net-corerazor-pagesef-core-3.0model-validation

ModelState is invalid for a nullable property


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; }
}

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

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

ModelState Invalid

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

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

many thanks

edit - the invalid object at time of validation


Solution

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

    For example, instead of sending the folowing json data:

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

    send only:

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

    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);
    

    See how it works:

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

    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).