I have a simple form that will upload multiple files. I have created a custom file type in order to store other relevant data in the upload and i am trying to validate the files uploaded but the model fails to bind from my custom file type so the model.isvalid always retus false
So i am trying to create a custom validation override that will work with my file structure but the value is always empty and i cant figure out the reason.
The file property is :
[Required(ErrorMessage = "Please select a file to upload")]
[Display(Name = "Upload Files")]
[ValidateFile]
public virtual ICollection<UserFile> Files { get; set; }
public class ValidateFileAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
int MaxContentLength = 1024 * 1024 * 3; //3 MB
string[] AllowedFileExtensions = new string[] { ".csv" };
var files = value as ICollection<UserFile>;
foreach(var asd in files){
var file = value as HttpPostedFileBase;
if (file == null)
retu false;
else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ErrorMessage = "Please upload Your File of type: " + string.Join(", ", AllowedFileExtensions);
retu false;
}
else if (file.ContentLength > MaxContentLength)
{
ErrorMessage = "Your File is too large, maximum allowed size is : " + (MaxContentLength / 1024).ToString() + "MB";
retu false;
}
}
retu true;
}
}
Custom type UserFile is defined as:
public class UserFile
{
[Key]
public Guid FileId { get; set; }
[StringLength(255)]
public string FileName { get; set; }
[StringLength(100)]
public string ContentType { get; set; }
public string Path { get; set; }
public FileType FileType { get; set; }
public virtual User User { get; set; }
}
My controller validation includes:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Send(User user, IEnumerable<HttpPostedFileBase> Files)
{
try
{
if (ModelState.IsValid)
{
I can use the Files from the post here but still the model validation fails.
Thank you in advance for any help, as i am trying to lea more about this type of validation. please let me know if further information is required
