문제

I followed this tutorial to create validation on HttpPostedFileBase, it works if I use HttpPostedFileBase, but if I changed to IEnumerable<HttpPostedFileBase> for uploading multiple files, and submit the form the ModelState.IsValid is always false. I uploaded .png file and size is 914 bytes. How to use data annotation to validate multiple file upload?

My Model

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;
            }
        }
    }
도움이 되었습니까?

해결책

It looks like you are casting the property to the wrong type.

Change this:

var file = value as HttpPostedFileBase;

to:

var files = value as IEnumerable<HttpPostedFileBase>;

and then you can iterate through each item in the collection and validate each file is the correct size.

다른 팁

Can you do something like

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

Catch: Won't work on client side

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top