尝试修改如下代码。
@Html.ValidationMessageFor(model => model.MyImage)
我的建议
您的表格应如下所示。
@using (Html.BeginForm("Acion", "Conroller", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<input type="file" name="FileInfo" value="File to Upload" />
@Html.ValidationMessageFor(I => I.FileInfo);
<button type="submit" name="Upload" value="Upload" />
}
HttpPostedFileBaseModelBinder
*当您将HttpPostedFileBase的单个实例作为操作参数或模型中的属性时,映射文件完全由HttpPostedFileBaseModelBinder完成,在这种情况下不使用任何值提供程序。您可能会想为什么在这种情况下没有使用 value provider,这是因为源是单一且明确的,即 Request.Files 集合。*
模型
public class UploadFileModel
{
[FileSize(10240)]
[FileTypes("jpg,jpeg,png")]
public HttpPostedFileBase FileInfo { get; set; }
}
文件大小属性
public class FileSizeAttribute : ValidationAttribute
{
private readonly int _maxSize;
public FileSizeAttribute(int maxSize)
{
_maxSize = maxSize;
}
public override bool IsValid(object value)
{
if (value == null) return true;
return _maxSize > (value as HttpPostedFileBase).ContentLength;
}
public override string FormatErrorMessage(string name)
{
return string.Format("The file size should not exceed {0}", _maxSize);
}
}
文件类型属性
public class FileTypesAttribute: ValidationAttribute
{
private readonly List<string> _types;
public FileTypesAttribute(string types)
{
_types = types.Split(',').ToList();
}
public override bool IsValid(object value)
{
if (value == null) return true;
var fileExt = System.IO
.Path
.GetExtension((value as
HttpPostedFileBase).FileName).Substring(1);
return _types.Contains(fileExt, StringComparer.OrdinalIgnoreCase);
}
public override string FormatErrorMessage(string name)
{
return string.Format("Invalid file type. Only the following types {0}
are supported.", String.Join(", ", _types));
}
}
控制器动作方法
[HttpPost]
public ActionResult Upload(UploadFileModel fileModel)
{
if(ModelState.IsValid)
{
}
return View(fileModel);
}