动态创建UIHint属性

时间:2011-09-06 14:21:27

标签: asp.net-mvc-3 attributes

我想动态地将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是否在后台对对象类型描述进行了任何缓存,可以解释这个事实?

在运行时将属性注入对象实例的任何其他建议吗?

1 个答案:

答案 0 :(得分:0)

这可能是因为“时机”。 尝试使用自定义ModelMetadataProvider以编程方式设置模型属性属性,如'UIHint'或'DisplayName'或... 看看here