mrDavid
mrDavid

Reputation: 77

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

Upvotes: 2

Views: 3216

Answers (3)

M.Ali El-Sayed
M.Ali El-Sayed

Reputation: 1779

In your code if you have input or select if you try to set the value with zero that could result in constrain problems in the database the solution is to set the value="" and why that work and just not setting the value at all result in validation error is due to that the validation check is running against the raw value which in our case will be string "null" not real null so just do

 <select asp-for="CustomerId" asp-items="@ViewBag.CustomersList" >
      <option value="">please select...</option>
</select>

that will solve the problem of wrong binding hope MS team take care of that next .net core version

Upvotes: 1

infografnet
infografnet

Reputation: 4005

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

Upvotes: 1

Moseyza
Moseyza

Reputation: 74

I had similar problem when my "CustomerId" was be selected from a select element. the problem was solved with setting value for the default option of the select:

<select asp-for="CustomerId" asp-items="@ViewBag.CustomersList" >
      <option value="0">please select...</option>
</select>

before setting value="0" for the default option in my action method the ModelState.IsValid always was false although the CustomerId property in the model was nullable.

Upvotes: 0

Related Questions