Why is my int? the value was checked as if it were required?

Do I have an int? View a model property that is being tested on the client side as if necessary. That is, if you leave the field blank, it will not be sent. The same does not happen for string properties.

HTML created for my editor:

<input type="text" value="" name="StatusIdSearch" id="StatusIdSearch" data-val-number="The field Status must be a number." data-val="true" class="text-box single-line"> 

I believe that data-val-number is throwing an error because nothing is a number, but I cannot determine why.

Any ideas?

Edit

View Model:

 public class CompromissoSearchModel { // other properties removed for the sake of clarity [Display(Name = "Status")] [EnumDataType(typeof(StatusCompromisso))] public int? StatusIdSearch { get; set; } // other properties removed for the sake of clarity } 
+6
source share
3 answers

The message you see is not associated with a mandatory field check. You do this because ClientDataTypeModelValidatorProvider adds the numerical validity of the client and ignores whether the type is null or not. You can check the code yourself :

 private static IEnumerable<ModelValidator> GetValidatorsImpl( ModelMetadata metadata, ControllerContext context) { Type type = metadata.RealModelType; if (IsNumericType(type)) { yield return new NumericModelValidator(metadata, context); } } 

And the implementation of IsNumericType :

 private static bool IsNumericType(Type type) { // strip off the Nullable<> Type underlyingType = Nullable.GetUnderlyingType(type); return _numericTypes.Contains(underlyingType ?? type); } 

Since nullable is not considered, you always get this check. As for the solution, you need to remove the ClientDataTypeModelValidatorProvider from the used providers or replace it with a regular one that does not ignore the NULL value.

+3
source

You can add the following code to your Application_Start method in the Global.asax file to fix this problem:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

+1
source

I had the same problem and managed to find a solution. None of these solutions worked for me, so I decided to publish the solution for everyone who has this problem.

The problem was not that the model binding checked the field as invalid, but when using TryUpdateModel, the nullable property in the viewmodel was not NULL in the database object.

A clearer explanation:

 TryUpdateModel(dbUser, "", new[]{ "DecimalProperty" })); 

The "DecimalProperty" in the viewmodel is NULL, but in dbUser it cannot be null.

0
source

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


All Articles