带有DataAnnotations的MVC模型验证 - 是否需要进行ICollection的任何方法?

Yab*_*rgo 3 data-annotations asp.net-mvc-3

我在Model类中有一个属性,如:

    /// <summary>
    /// A list of line items in the receipt
    /// </summary>      
    public ICollection<ReceiptItem> Items { get; set; }
Run Code Online (Sandbox Code Playgroud)

有没有什么办法可以标记这个属性来验证集合必须有1个或更多成员?我试图避免在ModelState.IsValid之外进行手动验证函数调用

Yab*_*rgo 9

我最终通过使用自定义DataAnnotation来解决问题 - 没想到看是否可以先完成!

这是我的代码,如果它可以帮助其他人!

/// <summary>
/// Require a minimum length, and optionally a maximum length, for any IEnumerable
/// </summary>
sealed public class CollectionMinimumLengthValidationAttribute : ValidationAttribute
{
    const string errorMessage = "{0} must contain at least {1} item(s).";
    const string errorMessageWithMax = "{0} must contain between {1} and {2} item(s).";
        int minLength;
        int? maxLength;          

        public CollectionMinimumLengthValidationAttribute(int min)
        {
            minLength = min;
            maxLength = null;
        }

        public CollectionMinimumLengthValidationAttribute(int min,int max)
        {
            minLength = min;
            maxLength = max;
        }

        //Override default FormatErrorMessage Method  
        public override string FormatErrorMessage(string name)
        {
            if(maxLength != null)
            {
                return string.Format(errorMessageWithMax,name,minLength,maxLength.Value);
            }
            else
            {
                return string.Format(errorMessage, name, minLength);
            }
        }  

    public override bool IsValid(object value)
    {
        IEnumerable<object> list = value as IEnumerable<object>;

        if (list != null && list.Count() >= minLength && (maxLength == null || list.Count() <= maxLength))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)