1

Closed

DataAnnotationsModelValidator.Validate does not set MemberName

description

DataAnnotationsModelValidator.Validate should set the MemberName property of the ValidationContext. Only DisplayName is set.

Current Code:
        public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
        {
            ValidationContext validationContext = new ValidationContext(container ?? metadata.Model, null, null)
            {
                DisplayName = metadata.GetDisplayName()
            };
            ValidationResult validationResult = this.Attribute.GetValidationResult(metadata.Model, validationContext);
            if (validationResult == ValidationResult.Success)
            {
                return new ModelValidationResult[0];
            }
            ModelValidationResult[] modelValidationResultArray = new ModelValidationResult[1];
            ModelValidationResult modelValidationResult = new ModelValidationResult()
            {
                Message = validationResult.ErrorMessage
            };
            modelValidationResultArray[0] = modelValidationResult;
            return modelValidationResultArray;
        }
There is:
            DisplayName = metadata.GetDisplayName()
GetDisplayName is defined as:
        public string GetDisplayName()
        {
            return this.PropertyName ?? this.ModelType.Name;
        }
As you can see, there is access to the property name. In normal circumstances PropertyName will be filled in. Please change the code to have this:
        ValidationContext validationContext = new ValidationContext(container ?? metadata.Model, null, null)
        {
            MemberName = metadata.PropertyName,
            DisplayName = metadata.GetDisplayName()
        };
Closed Feb 8 at 8:13 PM by pranavkm

comments