1

Custom Validator我为我的Response财产创建了一个。这是代码

public partial class MultipleSelectionQuestion<T> : Question
{
    private ICollection<T> _response;

    public int? MaxSelections
    {
        get { return ((MultipleSelectionQuestionTemplate<T>)this.QuestionTemplate).MaxSelections; }
    }

    public ICollection<T> Range
    {
        get { return ((MultipleSelectionQuestionTemplate<T>)this.QuestionTemplate).Range; }
    }

    [CustomValidation(typeof(CommonValidation), "ValidationMultipleSelectionResponseChoices")]
    [Required]
    public ICollection<T> Response
    {
        get { return _response; }
        set {  SetProperty(ref _response, value, "Response"); }
    }
}

这是我的CommonValidation静态类,我意识到Response属性找不到方法。问题是通用的。

public static class CommonValidation
{
    public static ValidationResult ValidationMultipleSelectionResponseChoices<T>(IEnumerable<T> value, ValidationContext context)
    {
        var question = (MultipleSelectionQuestion<T>)context.ObjectInstance;
        if (value != null)
        {
            var maxSelections = question.MaxSelections;

            if (maxSelections.HasValue)
            {
                if (value.Count() > maxSelections.Value)
                {
                    return new ValidationResult(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            "Response must have at most {0} selections",
                            maxSelections.Value),
                        new[] { context.MemberName });
                }
            }
        }

        return ValidationResult.Success;
    }
}
4

0 回答 0