嘗試修改如下面的代碼。
@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並且在這種情況下不使用值提供程序。您可能會想,爲什麼在這種情況下沒有使用值提供程序,這是因爲源代碼是單一且清晰的,即Request.Files集合。*
型號
public class UploadFileModel
{
[FileSize(10240)]
[FileTypes("jpg,jpeg,png")]
public HttpPostedFileBase FileInfo { get; set; }
}
FileSizeAttribute
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);
}
}
FileTypesAttribute
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);
}
什麼是錯誤 – ps2goat
它總是顯示爲一個錯誤,所以我不能使用MVC 4剃鬚刀後我的形式進出口 – ONYX
我不知道我不知道正則表達式的語法非常好所以我不知道 – ONYX