2

我的 MVC 3 Web 应用程序中有一个文件上传功能,我正在尝试使用这些属性验证 FileSize 和 FileType:

[FileSize(1048576, ErrorMessage = "The image is too big. It should be up to 1MB")]
[FileType(MimeTypes.Image.Jpg, MimeTypes.Image.Jpeg, MimeTypes.Image.Png, "image/pjpeg", "image/x-png", ErrorMessage = "Your image must be a JPG/JPEG or PNG up to 1MB.")]
public HttpPostedFileBase File { get; set; }

HTML如下:

<input type="file" size="20" name="File" />
@Html.ValidationMessageFor(x => x.File)

选择文件后一切正常。但是,如果没有选择文件,我仍然会触发 FileSize 或 FileType 验证并出现验证错误。由于我不希望在 POST 上需要 File,我该如何避免这种情况?

4

1 回答 1

4

您必须修改FileSizeFileType自定义验证属性,以便在值为 null 时不执行任何验证。例如:

public class FileSizeAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null)
        {
            // don't validate if value is null
            return null;
        }

        // TODO: do whatever validation you were supposed to do
        ...
    }
}

您可以通过该[Required]属性使该文件成为必需的。

于 2012-08-28T10:14:42.110 回答