如何验证IEnumerable使用数据注释

本文关键字:HttpPostedFiles 注释 数据 IEnumerable 何验证 验证 | 更新日期: 2023-09-27 18:02:57

我遵循本教程在HttpPostedFileBase上创建验证,如果我使用HttpPostedFileBase,它可以工作,但如果我更改为IEnumerable<HttpPostedFileBase>上传多个文件,并提交表单ModelState.IsValid总是假的。我上传了。png文件,大小是914字节。如何使用数据注释来验证多个文件上传?

我的模型
public class BillingViewModel
{
     [Required]
     public long BillingID { get; set; }    
     public IEnumerable<TimeKeeper> TimeKeepers { get; set; }    
     [Required]
     [ValidateFile]
     public IEnumerable<HttpPostedFileBase> PostedFiles { get; set; }
}

ValidateFile.cs:

public class ValidateFileAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            int MaxContentLength = 1024 * 1024 * 3; //3 MB
            string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
            var file = value as HttpPostedFileBase;
            if (file == null)
            {
                return false;
            }
            else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
            {
                ErrorMessage = "Please upload Your Photo of type: " + string.Join(", ", AllowedFileExtensions);
                return false;
            }
            else if (file.ContentLength > MaxContentLength)
            {
                ErrorMessage = "Your Photo is too large, maximum allowed size is : " + (MaxContentLength / 1024).ToString() + "MB";
                return false;
            }
            else
            {
                return true;
            }
        }
    }

如何验证IEnumerable<HttpPostedFiles>使用数据注释

看起来您将属性转换为错误的类型。

改变:

var file = value as HttpPostedFileBase;

:

var files = value as IEnumerable<HttpPostedFileBase>;

,然后可以遍历集合中的每个项,并验证每个文件的大小是否正确。

你能不能做点像

[Required]
public int? ListCount
{
 get {return PostedFiles == null || PostedFiles.Count()==0? (int?)null: PostedFiles.Count();}
}

Catch: Won't work on client

相关文章:
  • 没有找到相关文章