开发者

Obtain containing object instance from ModelMetadataProvider in ASP.NET MVC

Implementing custom DataAnnotationsModelMetadataProvider in ASP.NET MVC2.

Assuming the object that is b开发者_如何学JAVAeing 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.


Isn't it what modelAccessor parameter is for?

Try:

var containerInstance = modelAccessor() as IUpdateable;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜