Net MVC 3 для разработки.
Теперь есть сценарий, в котором мне нужно создать пользовательский валидатор для свойства коллекции.
Теперь проблема, с которой я сталкиваюсь, состоит в том, что этот пользовательский валидатор работает хорошо, когда длина коллекции равна 1, но когда в коллекции больше одного элемента, я сталкиваюсь с проблемой, когда пользовательская проверка выдает ошибки, но возникает проблема, которая при включении ModelState ошибка не найдена подключена. Так что в этом случае что мне делать? Я вставляю в код, как показано ниже.
Это модель, которую я хочу проверить:
public class CreateTestModel
{
[Required]
public string Name { get; set; }
public string Description { get; set; }
public RadioButtonListViewModel<GoalTypes> Goals { get; set; }
[MinimumRequired("IncludedEntities", "ExcludedEntities", 1, ErrorMessage = "1 Entity is compulsory")]
public IEnumerable<TestEntityModel> IncludedEntities { get; set; }
public IEnumerable<TestEntityModel> ExcludedEntities { get; set; }
public IEnumerable<TestFilterModel> IncludedFilters { get; set; }
public IEnumerable<TestFilterModel> ExcludedFilters { get; set; }
public IEnumerable<BucketModel> Buckets { get; set; }
public bool AutoDecision { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int AdminId { get; set; }
[DefaultValue(true)]
public bool IsEnabled { get; set; }
}
Назначение специального валидатора: -
Мне нужно проверить минимальное количество обязательных объектов в коллекции.
Существуют некоторые сценарии, когда, например, в этом случае: IncludedEntities и ExcludedEntities должны иметь минимальное число 1, включая оба свойства, это мое бизнес-правило.
Так что для этого написано ниже пользовательский валидатор.
Это пользовательский валидатор, который я написал:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MinimumRequired : ValidationAttribute,IClientValidatable
{
public int numberOfMandatoryEntities{get; private set;}
public int totalCountofIncludeEntities { get; private set; }
public bool isBucket { get; set; }
public string Property1{get; private set;}
public string Property2{ get; private set; }
private const string DefaultErrorMessageFormatString = "Atleast one entity is required";
public MinimumRequired(string Property1, string Property2, int MandatoryCount)
{
this.Property1 = Property1;
if (!String.IsNullOrEmpty(Property2))
this.Property2 = Property2;
numberOfMandatoryEntities = MandatoryCount;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
object property2Value = null;
object property1Value = null;
int property1Count=0;
if(!String.IsNullOrEmpty(Property2))
property2Value = validationContext.ObjectInstance.GetType().GetProperty(Property2).GetValue(validationContext.ObjectInstance, null);
property1Value = validationContext.ObjectInstance.GetType().GetProperty(Property1).GetValue(validationContext.ObjectInstance, null);
if (property1Value != null)
{
property1Count = ((IEnumerable<Object>)property1Value).Count();
}
if (property2Value != null)
{
property1Count = property1Count + ((IEnumerable<Object>)property2Value).Count();
}
if (property1Count < numberOfMandatoryEntities)
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
#region IClientValidatable Members
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var x = new ModelClientValidationRule();
x.ValidationType = "entityvalidator";
x.ErrorMessage = string.Format(ErrorMessageString, metadata.GetDisplayName());
x.ValidationParameters.Add("mandatoryentity", numberOfMandatoryEntities);
return new[]
{
x
};
}
#endregion
}
Пожалуйста, помогите мне ...