自定义“至少”属性

时间:2014-09-10 14:20:33

标签: c# asp.net-mvc

我正在尝试创建一个属性来验证我的模型。

在我的模型中,我有一个列表。该列表必须具有与标准匹配的确定数量的项目,例如“至少1个活动项目”或“至少1个活动项目,其中”John“作为其名称”。

我的代码是这样的:

public class Foo
{
    [AtLeast(1, new Tuple<string, object>("Active", true))]
    public List<Item> ListOfSomething { get; set; }

    [AtLeast(1, new Tuple<string, object>("Active", true), new Tuple<string, object>("Name", "John"))]
    public List<Item> AnotherList { get; set; }
}

public class Item
{
    public string Name { get; set; }
    public bool Active { get; set; }
}
public class AtLeastAttribute : ValidationAttribute
{
    public int MinLength { get; set; }
    public Tuple<string, object>[] PropertiesAndValues { get; set; }


    public AtLeastAttribute(int minLength,params Tuple<string, object>[] propsNValues)
    {
        MinLength = minLength;
        PropertiesAndValues = propsNValues;
    }
}

我试图传递一个Tuple<string, object>来表示该属性和所需值。但是我收到了这个错误:

  

属性参数必须是常量表达式,typeof表达式   或属性参数类型

的数组创建表达式

任何人都有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

同意DavidG的评论;唯一的方法是提供某种常量创建表达式,基本上限制了原始类型。如果要实现此功能,则指定的所有约束值都应该可以从字符串中转换。

然后你可以想到一些像

这样的语法
Name=John;Active=True

但事情并非如此简单,您可能希望在字符串值中包含;=,因此您需要找出一些字符串语法和转义字符:

Name='John\\'s Pizza'

Name='John''s Pizza'

然后你需要解析这些信息;正则表达式也许能够做到。

如果你没有包含用于分割的字符的字符串值,只需将字符串拆分为;,然后=和presto。