Implementing custom DataAnnotationsModelMetadataProvider
in ASP.NET MVC2.
Assuming the object that is being rendered looks like this:
- Contact : IUpdateable
- Name: string
- ContactType: (Lead, Prospect, Customer)
and the method below is in the context of Contact.ContactType
meaning that:
meta.PropertyName == "ContactType"
meta.ContainerType == typeof(Contact)
meta.Model == ContactType.Lead
(the code under question:)
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes,
Type containerType,
Func<object> modelAccessor,
Type modelType, string propertyName) {
var containerInstance = meta.NotSureWhatGoesHere as IUpdateable;
meta.IsReadOnly = containerInstance != null && containerInstance.CanBeUpdated(meta.PropertyName);
}
The question: How can I obtain the instance of Contact from the metadata? (replace NotSureWhatGoesHere
with the correct one)?
Thanks.
The dirty way (tested in mvc3):
object target = modelAccessor.Target;
object container = target.GetType().GetField("container").GetValue(target);
It will return the model in model => model.Contact.Name instead of model.Contact. The rest is left as an exercise to the reader ;). This method comes, as all reflection based solutions poking around in non public data, without warranty.
I don't think you can. I asked Brad Wilson (author of ModelMetadata
, et. al.) about this directly, and he couldn't come up with a way. I eventually had to go a different route.
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