MetadataType and client validation in ASP.NET MVC 2

前端 未结 3 1911
刺人心
刺人心 2021-01-13 02:31

Inherited properties and MetadataType does not seem to work with client side validation in ASP.NET MVC 2.

The validation of our MetadataTypes work a

3条回答
  •  清歌不尽
    2021-01-13 03:00

    Maybe it's too late but this is the way I managed to solve this bug.
    I've created a custom model metadata provider that inherits from DataAnnotationsModelMetadataProvider and override the CreateMetadata method. The problem is that the value in containerType parameter points to the base class instead of pointing to inherited class. Here is the code

    public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(
            IEnumerable attributes, 
            Type containerType, 
            Func modelAccessor, 
            Type modelType, 
            string propertyName)
        {
    
            if (modelAccessor != null && containerType != null)
            {                
                FieldInfo container = modelAccessor.Target.GetType().GetField("container");
                if (containerType.IsAssignableFrom(container.FieldType))
                    containerType = container.FieldType;
            }
    
            var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
    
    
    
            return modelMetadata;
        }
    }
    
    
    

    And finally we have to register this custom metadata provider in Global.asax at Application_Start

    ModelMetadataProviders.Current = new CustomModelMetadataProvider();
    

    Sorry for my English!

    提交回复
    热议问题