我想要动态地将UIHint属性注入模型对象。我一直在使用ICustomTypeDescriptor创建一个类,该类将把UIHint注入到一个对象的实例中:
public sealed class UIHintDescriptionProvider : TypeDescriptionProvider
{
private string PropertyName;
private string HintValue;
public UIHintDescriptionProvider(TypeDescriptionProvider parent, string propertyName, string hintValue)
: base(parent)
{
this.PropertyName = propertyName;
this.HintValue = hintValue;
}
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
return new UIHintDescriptor(base.GetTypeDescriptor(objectType, instance), this.PropertyName, this.HintValue);
}
}
public sealed class UIHintDescriptor : CustomTypeDescriptor
{
private string PropertyName;
private string HintValue;
internal UIHintDescriptor(ICustomTypeDescriptor parent, string propertyName, string hintValue)
: base(parent)
{
this.PropertyName = propertyName;
this.HintValue = hintValue;
}
public override PropertyDescriptorCollection GetProperties()
{
// Enumerate the original set of properties and create our new set with it
PropertyDescriptorCollection originalProperties = base.GetProperties();
List<PropertyDescriptor> newProperties = new List<PropertyDescriptor>();
foreach (PropertyDescriptor pd in originalProperties)
{
if (pd.Name == this.PropertyName)
{
Attribute attr = new UIHintAttribute(this.HintValue);
var newProp = TypeDescriptor.CreateProperty(typeof(object), pd, attr);
newProperties.Add(newProp);
}
else
{
newProperties.Add(pd);
}
}
// Finally return the list
return new PropertyDescriptorCollection(newProperties.ToArray(), true);
}
}然后我在我的控制器中使用以下命令进行设置:
UIHintDescriptionProvider provider =
new UIHintDescriptionProvider(TypeDescriptor.GetProvider(typeof(PageContentItem)), "Text",
"wysiwyg");
TypeDescriptor.AddProvider(provider, item);使用TypeDescriptor函数在此对象的控制器中进行的检查表明,确实已经设置了此属性,但是它根本没有出现在我的视图中。单步执行MVC3源代码会显示所有其他属性,但不是我刚才设置的属性。
MVC3是否会在后台缓存对象类型描述,以说明这一事实?
关于在运行时将属性注入到对象实例中,还有其他建议吗?
发布于 2012-06-25 14:48:03
这可能是因为“时机”的原因。尝试使用自定义ModelMetadataProvider以编程方式设置模型属性属性,如“UIHint”或“DisplayName”或...看一下here。
https://stackoverflow.com/questions/7321452
复制相似问题