1

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

mrDavid
  • 47
  • 7
  • Your CompanyID field is not [Required], so it should not be the reason of invald ModelState. Check your ReportTemplateID filed, is it having any value when Post. – Sh.Imran Jul 22 '20 at 15:00
  • @Imran `ReportTemplateID` will always satisfy `Required` if i remember correctly, no matter if it is passed or not. – Guru Stron Jul 22 '20 at 15:05
  • I would say that for some reason `"null"` is passed for `CompanyID` which can't be turned into valid `int?` – Guru Stron Jul 22 '20 at 15:11
  • @Imran, I'd like to CompanyID to be accepted as null, so I have omitted [Required] – mrDavid Jul 22 '20 at 15:14
  • Please add your form code. – Guru Stron Jul 22 '20 at 15:14
  • @mrDavid you should change CompanyID type from int? to string. Your problem will be solved, I think. – Sh.Imran Jul 22 '20 at 15:18
  • @GuruStron, you are correct. Seems a javascript null added to a string is "null", go figure. If you add an answer i'll mark it correct. Thankyou both for the feedback – mrDavid Jul 22 '20 at 23:16

3 Answers3

1

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

M.Ali El-Sayed
  • 1,608
  • 20
  • 23
0

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.

Moseyza
  • 72
  • 12
0

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

infografnet
  • 3,749
  • 1
  • 35
  • 35
  • it is failing in .NET 6 for me. I have nullable string parameter with default value and omitting it from the request url does not help. The model validation still fails it. – RedRose Apr 24 '23 at 07:47