我在 ASP.net Core 上有一个多选列表,但无法进行验证

I have a Multiselect list on ASP.net Core and validaton is not woking

我有一个 select 字段

<select asp-for="UserCitizenships" asp-items="Model.CitizenshipsList" class="select2 required">

由多个select 列表

填充
public MultiSelectList CitizenshipsList { get; set; }

和returns一个整数列表

 public List<int> UserCitizenships

我在后台手动处理。数据注释的验证不起作用。当表单提交时,我至少需要一个 属性 来填充。有什么想法吗?

  [Required(ErrorMessage = Helpers.ErrorMessages.Required)]
    public List<int> UserCitizenships
    {
        get
        {
           ....

我原以为以下方法可行

[Required, MinLength(1, ErrorMessage = "At least one item required")]
public List<int> UserCitizenships { get; set; }

或者,您可以创建自定义数据注释或使用 class 级别验证

public class YourClass : IValidatableObject
{
    [Required]
    List<int> UserCitizenships

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (UserCitizenships.Count < 1)
        {
            yield return new ValidationResult(
                $"At least one UserCitizenship should be specified.",
                new[] { nameof(UserCitizenships) });
        }
    }   
}