A
A
Artem D2018-06-30 21:01:26
ASP.NET
Artem D, 2018-06-30 21:01:26

ASP.NET MVC why does model validation ( Validator.TryValidateObject ) contain default ErrorMessages and not our own?

asp.net mvc 5 application.
global.asax defines custom adapter for RequiredAttribute

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(CustomRequiredAttributeAdapter));

CustomRequiredAttributeAdapter:
public CustomRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
            : base(metadata, context, attribute)
        {
            if (string.IsNullOrEmpty(attribute.ErrorMessage))
            {
                attribute.ErrorMessageResourceType = typeof(ValidationResources);
                attribute.ErrorMessageResourceName = "RequiredAttribute_ValidationError";
            }
        }

There is App_GlobalResources/ValidationResources.resx which defines its own ErrorMessages for the validator: The
5b37c3c8ea776063867147.png
controller method is called, in which the model is checked for validity -
...
var isValid = Validator.TryValidateObject(instance, validationContext, validationResults, true);
...
But the results of the check contain the default texts of the framework!
5b37c4627d70d404132572.png
Wherein! If we run the same controller method again and again, already in this case, the result of the model check will be our own error texts (as it should be).
5b37c4ce4f7ce040299592.png
Why does this happen in 1 call?
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Pavlov, 2018-07-05
@dmitry_pavlov

Only one of them should be set - either ErrorMessageString or ErrorMessageResourceName - but not both. Try explicitly setting ErrorMessage to null. Something like this:

[Required(ErrorMessage = null, ErrorMessageResourceName = “RequiredAttribute_ValidationError”, ErrorMessageResourceType = typeof(ValidationResources))]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question