我正在尝试使用简单的bool结果创建自定义数据注释属性,如果属性具有数据注释,则执行操作。我的目标是创建一个包含所有具有Filter dataanotation属性的数组,以便稍后使用该信息生成DropDownListFor。
public class Foo
{
public string property1 { get; set; }
[Filter]
public string property2 { get; set; }
}
然后在代码的某处:
IList<PropertyInfo> properties = typeof(Foo).GetProperties().ToList();
ArrayList propertiesThatCanBeFiltered = new ArrayList();
foreach (var propertyInfo in properties)
{
if (propertyInfo.Attributes("Filter").Exists)
{
propertiesThatCanBeFiltered.Add(propertyInfo.Name);
}
}
答案 0 :(得分:0)
您需要GetCustomAttribute<T>
Documentation
以下是如何应用它:
IList<PropertyInfo> properties = typeof(Foo).GetProperties().ToList();
ArrayList propertiesThatCanBeFiltered = new ArrayList();
foreach (var propertyInfo in properties)
{
var filterAttribute = propertyInfo.GetCustomAttribute<Filter>();
if (filterAttribute != null)
{
propertiesThatCanBeFiltered.Add(propertyInfo.Name);
}
}
答案 1 :(得分:-1)
我相信自定义ActionFilters就是您的目标:
http://msdn.microsoft.com/en-us/library/dd410056(v=vs.100).aspx
这就是你在问题中说明何时应用某个属性然后执行某些逻辑... AF&#39; s就是这样。
除此之外,还有一种方法可以创建自己的自定义数据注释:
How to create Custom Data Annotation Validators
http://weblogs.asp.net/brijmohan/asp-net-mvc-3-custom-validation-using-data-annotations
但这完全取决于你想做什么。不要把2混在一起。