What does it mean for a property to be [Required] and nullable?
Solution 1:
The reason for making a property nullable and marked with the [Required]
attribute is to protect against under-posting attacks. It also allows you to display an initial empty value in the view rather than the default value for the property. This is typically done with value type properties in view models.
An under-posting attack is where a malicious user modifies the request to omit a value for the property in the request. If the property was DateTime
(not nullable), then the DefaultModelBinder
will initialize the value its default (01/01/0001
) and no ModelState
error would be generated. As a result, that value may then be saved even though its not what you may be expecting.
If the property is DateTime?
(nullable) and [Required]
, then if a malicious user did omit the property in the request, then a ModelState
error will be generated because a value is expected in the request, and the view would be returned, therefore the invalid data will not be saved.
Refer also Brad Wilson's article Input Validation vs. Model Validation in ASP.NET MVC and the section titled The "Under-Posting" Problem.
Solution 2:
It's nullable so the form doesn't display an initial value like 0001-01-01T00:00:00
that has no meaning.
It's required to force the user to enter something.