ModelMetadata.Container property is null

1.2k views Asked by At

I am writing a custom ModelMetadataProvider which extends default DataAnnotationsModelMetadataProvider. Unfortunately i came across an issue: ModelMetadata.Container property is always null. According to msdn description of ModelMetadata Class, container property should not be null when model represents a property:

enter image description here

But when overriding GetMetadataForProperty method, after calling base implementation Container property always returns as null:

enter image description here

protected override ModelMetadata GetMetadataForProperty(
            Func<object> modelAccessor, 
            Type containerType, 
            PropertyDescriptor propertyDescriptor)
        {
            ModelMetadata metadata = base.GetMetadataForProperty(modelAccessor, containerType, propertyDescriptor); 

            // metadata.Container always null here                
        }

On the other way, when accessing ModelMetadata from ViewData, Container property gets filled as expected:

enter image description here

Thus I have couple of questions related to this issue:

  1. Is it an expected behavior that ModelMetadata.Container returns empty from GetMetadataForProperty or it is a bug?

  2. Is there a way to get ModelMetadata.Container property filled inside ModelMetadataProvider?

  3. When ModelMetadata.Container property actually gets it's content?

1

There are 1 answers

4
AudioBubble On

Metadata is created from the innermost properties out, so the container model's metadata has not yet been created at the time GetMetadataForProperty is called (the same applies for OnMetadataCreated when you implement IMetadatAware). The reason you can acess it from ViewData is that the process of creating all metadata has been completed.