【问题标题】:Custom Data Annotation attribute bool check自定义数据注释属性布尔检查
【发布时间】:2015-01-14 15:22:09
【问题描述】:

我正在尝试使用简单的布尔结果制作自定义数据注释属性,如果属性具有数据注释,则执行操作。我的目标是创建一个包含所有具有过滤器数据注释的属性的数组,以便稍后根据该信息创建一个 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);
            }

        }

【问题讨论】:

标签: asp.net asp.net-mvc entity-framework data-annotations


【解决方案1】:

你需要GetCustomAttribute&lt;T&gt;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);
    }

}

【讨论】:

  • 感谢您的信息,我现在的问题是我在元数据中设置了数据注释,并且在那里不起作用。
  • 嗯,这听起来像是另一个问题。
  • 是的,是的,我想赞成你的回答,但我没有权利 =(
  • 别担心这些虚拟网点,反正它们一文不值。
【解决方案2】:

我相信自定义 ActionFilters 是您所追求的:

http://msdn.microsoft.com/en-us/library/dd410056(v=vs.100).aspx

这就是您在问题中所说的,当应用某个属性然后执行一些逻辑时……AF 就是这样做的。

除此之外,还有一种方法可以创建您自己的自定义数据注释:

How to create Custom Data Annotation Validators

http://weblogs.asp.net/brijmohan/asp-net-mvc-3-custom-validation-using-data-annotations

但这完全取决于您想要做什么。不要把两者混在一起。

【讨论】:

  • 问题是,我根本不需要检查或过滤 ActionResult 或 Action,我需要制作一个 DropDownList,其中仅包含带有“Filter”的模型对象的属性。
  • 您需要进一步详细说明您到底想要什么。是什么让你认为一个属性会为这个上下文做你想要的? :)
  • 好吧,我解释得更好了 =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多