1.使用验证特性
[RequiredCollection]
public ICollection<IFormFile> Attachments { get; set; }
2.自定义验证特性
public class RequiredCollectionAttribute : ValidationAttribute
{
protected const string DefaultErrorMessageFormatString = "You must provide at least one."; public RequiredCollectionAttribute() : base(DefaultErrorMessageFormatString) { } protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var collection = (ICollection) value; return collection == null || collection.Count >
? ValidationResult.Success
: new ValidationResult(ErrorMessageString);
}
}
3.提交请求验证
[HttpPost]
public async Task<IActionResult> Method(MethodViewModel viewModel)
{
if (!ModelState.IsValid)
return View(viewModel);
...
}
原文链接:http://*.com/questions/35989885/mvc-icollectioniformfile-validationstate-always-set-to-skipped