当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - How to validate IEnumerable<HttpPostedFiles> using Data Annotation

问题描述:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: