How does AddImplicitRequiredAttributeForValueTypes work and what is it for?

Here is a description (ASP.NET MVC 3):

  • I have this parameter DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes in the default value true (checked with a debugger)

  • I have a value type field in my model ( int , DateTime , decimal ):

     public class MyModel { public int SomeField { get; set; } } 
  • When I submit an empty form to this action (no SomeField ):

      public ActionResult Submit(MyModel request) { if (ModelState.IsValid) { .. } else { .. } } 
  • I have no verification errors! It seems logical to me - the default value of int is 0 . This is the value.

Questions:

If I want this value to always be set in the request, I have to make it nullable and put [Required] on it, this works. But what is DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes for?

+4
source share
1 answer

If we refer to ASP.NET MVC sources, DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes checked only in the DataAnnotationsModelValidatorProvider.Getvalidators method , which provides validation metadata for HTML HTML helpers (when rendering the attributes DataModel *).

Thus, DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes can be set when it is necessary to change the client-side validation behavior and allow the transmission of empty values โ€‹โ€‹(that is, the field is published, but does not matter) for the value types for the controller action.

+2
source

Source: https://habr.com/ru/post/1396817/


All Articles