在MetadataProvider中获取相同类型的多个属性

时间:2016-05-08 20:43:13

标签: c# asp.net-mvc metadata custom-attributes

我有一个属性,有class AutoSizeUIButton: UIButton{ override func intrinsicContentSize() -> CGSize { return CGSizeMake(self.frame.size.width, self.titleLabel!.frame.size.height) } } networkButton.setTitle("something-here", forState: .Normal) networkButton.titleLabel?.font = UIFont(name: "HelveticaNeue", size: 20.0)! let networkSize = networkButton.intrinsicContentSize() print("button size", networkSize.width, networkSize.height) //prints 0.0, 0.0

AllowMultiple

我多次在我的房产上使用它:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class AllowedDeviceTypesAttribute : System.Attribute
{
    //...
}

我有自定义模型元数据提供程序:

[AllowedDeviceTypes(DeviceTypes.StaticRegister)]
[AllowedDeviceTypes(DeviceTypes.MobileRegister)]
public int ClientNr { get; set; }

我的问题是,我public class ExtendedModelMetadataProvider : DataAnnotationsModelMetadataProvider { protected override ModelMetadata CreateMetadata(IEnumerable<System.Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) { var attributeList = attributes as IList<System.Attribute> ?? attributes.ToList(); var data = base.CreateMetadata(attributeList, containerType, modelAccessor, modelType, propertyName); //... var allowedDeviceTypesAttributes = attributeList.Where(a => typeof(AllowedDeviceTypesAttribute) == a.GetType()).ToList(); if (allowedDeviceTypesAttributes.Count > 0) { var allowedDeviceTypes = allowedDeviceTypesAttributes.Cast<AllowedDeviceTypesAttribute>().Select(e => e.AllowedDeviceType).ToList(); data.AdditionalValues.Add(AllowedDeviceTypesAttribute.AdditionalMetaDataValue, allowedDeviceTypes); } return data; } } 中只有一个AllowedDeviceTypesAttribute

enter image description here

我如何获得这两个属性?

attributes

1 个答案:

答案 0 :(得分:1)

为了完成这项工作,我们需要覆盖TypeId属性:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class AllowedDeviceTypesAttribute : System.Attribute
{
    //...
    public override object TypeId
    {
        get
        {
            return this;
        }
    }
}