I have an int? view model property that is validated at client-side as if it was required. That is, if I leave the field blank, it will not submit. The same does not happen for string properties.
The HTML rendered for my editor is:
<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 causing an error because nothing is not a number, but I cannot determine why.
Any ideas?
Edit
The 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
}
The message you are seeing it's not related to a required field validation. You're gettings this because ClientDataTypeModelValidatorProvider
adds client numeric validation and it ignores if the type is nullable or nor 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 IsNumericType
implementation:
private static bool IsNumericType(Type type)
{
// strip off the Nullable<>
Type underlyingType = Nullable.GetUnderlyingType(type);
return _numericTypes.Contains(underlyingType ?? type);
}
Since the nullable is not considered you always get that validation. In terms of solution, you need to remove ClientDataTypeModelValidatorProvider
from the used providers or maybe replace it with a custom one that does not ignore nullable.
You should be able to add the following code to your Application_Start
method in Global.asax file to fix this issue:
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With