Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 316
Dmytrii Nagirniak Avatar asked Mar 09 '11 03:03

Dmytrii Nagirniak


2 Answers

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.

like image 61
Sjaaky Avatar answered Nov 19 '22 04:11

Sjaaky


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.

like image 22
Craig Stuntz Avatar answered Nov 19 '22 05:11

Craig Stuntz