The validation system treats non-nullable parameters or bound properties as if they had a [Required(AllowEmptyStrings = true)]
attribute. By enabling Nullable
contexts, MVC implicitly starts validating non-nullable properties or parameters as if they had been attributed with the [Required(AllowEmptyStrings = true)]
attribute. Consider the following code:
public class Person
{
public string Name { get; set; }
}
If the app was built with <Nullable>enable</Nullable>
, a missing value for Name
in a JSON or form post results in a validation error. This may seem contradictory since the [Required(AllowEmptyStrings = true)]
attribute is implied, but this is expected behavior because empty strings are converted to null by default. Use a nullable reference type to allow null or missing values to be specified for the Name
property:
public class Person
{
public string? Name { get; set; }
}