Here is a description (ASP.NET MVC 3):
-
I have this parameter
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypesin the default valuetrue(checked with the debugger) -
I have value-type field in my model (
int,DateTime,decimal):public class MyModel { public int SomeField { get; set; } } -
When I post empty form to this action (no
SomeFieldspecified):public ActionResult Submit(MyModel request) { if (ModelState.IsValid) { .. } else { .. } } -
I don’t have any validation errors! It seems to me logical — the default value of int is
0. Which is a value.
Questions:
If I want to force this value always expicitly set in request I should make it nullable and put [Required] on it, this works. But what DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes is for?
If we refer to ASP.NET MVC sources,
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypesis checked only in DataAnnotationsModelValidatorProvider.Getvalidators method which provides validation metadata for HTML Helpers (when rendering data-val-* attributes) and DefaultModelBinder.So,
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypescould be set when there is need to change behaviour of client-side validation and allow passing empty values(i.e. field is posted but has no value set) for value types to controller action.