【发布时间】:2014-05-12 11:14:02
【问题描述】:
我按照tutorial 在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;
}
}
}
【问题讨论】:
标签: c# asp.net-mvc validation