如何从 ValidationAttribute class 的 IsValid 函数访问 ModelState.AddModelError()

How to access ModelState.AddModelError() from IsValid function of ValidationAttribute class

我尝试在 ValidationAttribute class 的 IsValid 函数中添加这一行 ModelState.AddModelError(string key, string errorMessage); 但失败了。

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
    public class AtleastOneAttribute : ValidationAttribute, IClientValidatable
    {
        // For Server side
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                var oHobby=value as IEnumerable;

                foreach (var _object in oHobby)
                {
                    Hobby _oHobby = (Hobby)_object;
                    if (_oHobby.IsSelected)
                    {
                        return ValidationResult.Success;
                    }
                }

            }
             ModelState.AddModelError("Hobbies", "Err message....");

            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }

告诉我如何从 ValidationAttribute class 的 IsValid 函数访问 ModelState.AddModelError

谢谢

ModelState 无法在 IsValid 函数中访问。 IsValid 方法通过它的 return 语句向 ModelState 添加错误,因此如果您需要添加错误,只需 return 它:

return new ValidationResult("Err message....");