Валидатор
Код: Выделить всё
public class RequiredAtLeasOneFromCollectionAttribute : ValidationAttribute, IClientModelValidator
{
public RequiredAtLeasOneFromCollectionAttribute()
{
ErrorMessage = "Please select at least one"; //used if error message is not set on attribute itself
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
List list = value as List;
if (list.IsNull() || !list.Any(x => x.IsSelected))
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
public void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-requiredonefromcollection", errorMessage);
}
private bool MergeAttribute(IDictionary attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
Код: Выделить всё
public class CampaignType
{
[Required]
public int CampaignTypeId { get; set; }
[Required]
public string CampaignTypeName { get; set; }
[Required]
public bool IsActive { get; set; }
public bool IsSelected { get; set; } = true;
}
Код: Выделить всё
public class Affiliate
{
[Required]
public int Id { get; set; }
[RequiredAtLeasOneFromCollectionAttribute]
List Campaigns {get; set}
//Assume Constructor fills Campaigns
}
Код: Выделить всё
@for(int i = 0; i < Model.Affiliate.Campaigns.Count; i++)
{
@Model.Affiliate.Campaigns[i].CampaignTypeName
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... n-property
Мобильная версия