获得含有对象实例从ModelMetadataProvider在ASP.NET MVC [英] Obtain containing object instance from ModelMetadataProvider in ASP.NET MVC
问题描述
实施ASP.NET MVC2定制 DataAnnotationsModelMetadataProvider
。
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)
和下面的方法是在上下文 Contact.ContactType
这意味着:
and the method below is in the context of Contact.ContactType
meaning that:
-
meta.PropertyName ==ContactType
-
meta.ContainerType == typeof运算(联系方式)
-
meta.Model == ContactType.Lead
meta.PropertyName == "ContactType"
meta.ContainerType == typeof(Contact)
meta.Model == ContactType.Lead
(下讨论的code:)
(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);
}
问题:我怎样才能从元数据取得联系的实例的? (用正确的替换 NotSureWhatGoesHere
)?
The question: How can I obtain the instance of Contact from the metadata? (replace NotSureWhatGoesHere
with the correct one)?
感谢。
推荐答案
在肮脏的方式(在MVC3测试):
The dirty way (tested in mvc3):
object target = modelAccessor.Target;
object container = target.GetType().GetField("container").GetValue(target);
这将返回模式 模型=> model.Contact.Name 的model.Contact代替。剩下的就留给读者做练习)。这种方法来了,因为所有的反射解决方案在非公开的数据闲逛,不附带。
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.
这篇关于获得含有对象实例从ModelMetadataProvider在ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!