我目前正在使用以下代码来验证上传的文件是否属于某种类型。但是,使用Validation.IsValid的代码似乎允许一切通过,因此将代码上传到系统。
有人可以提供一些帮助吗?
使用@HTML.ValidationMessage我可以看到错误验证发生(即只允许CSV)
谢谢
@using Microsoft.Web.Helpers;
@{
if(IsPost && @System.Web.HttpContext.Current.User.IsInRole("EHM\\Domain Admins")) {
if(Request.Files[0].ContentLength == 0){
ModelState.AddError("fileUpload", "You must upload a file");
} else {
var allowedExtensions = new[]{".csv"};
var extension = Path.GetExtension(Request.Files[0].FileName.ToLower());
if(!allowedExtensions.Contains(extension)){
ModelState.AddError("fileUpload", "Only CSV are allowed");
}
}
if(Validation.IsValid()) {
var fileName = "";
var fileSavePath = "";
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/App_Data/UploadedFiles/" + fileName);
uploadedFile.SaveAs(fileSavePath);
}
else {
<p class="bg-danger"> File has not been uploaded </p>
}
}
}
edfef
@FileUpload.GetHtml(
initialNumberOfFiles:1,
allowMoreFilesToBeAdded:false,
includeFormTag:true,
uploadText:"Upload CSV only")
@Html.ValidationMessage("fileUpload")
答案 0 :(得分:0)
试试这个
ModelState.AddModelError(string.Empty, "Only CSV are allowed");
而不是
ModelState.AddError("fileUpload", "Only CSV are allowed");
使用空键添加模型错误,而不是将其绑定到特定属性。
注意:通常最好将正确的属性添加到ViewModel中并对该属性执行验证。