Dmytrii Nagirniak
Dmytrii Nagirniak

Reputation: 24108

Obtain containing object instance from ModelMetadataProvider in ASP.NET MVC

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:

(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.

Upvotes: 14

Views: 2456

Answers (3)

Sjaaky
Sjaaky

Reputation: 166

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.

Upvotes: 11

Craig Stuntz
Craig Stuntz

Reputation: 126567

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.

Upvotes: 2

Jakub Konecki
Jakub Konecki

Reputation: 46008

Isn't it what modelAccessor parameter is for?

Try:

var containerInstance = modelAccessor() as IUpdateable;

Upvotes: 0

Related Questions