0
我目前使用下面的代碼來驗證上傳的文件是一種特定的類型。但是,使用Validation.IsValid的代碼似乎允許一切通過,並因此將代碼上傳到系統。Validation.IsValid()不驗證錯誤剃刀C#
有人請提供一些幫助嗎?
使用@ 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")
嗨mok,我已經嘗試了上述,但我得到以下編譯錯誤。我需要什麼依賴關係? CS1061:'System.Web.WebPages.Html.ModelStateDictionary'不包含'AddModelError'的定義,並且沒有找到接受'System.Web.WebPages.Html.ModelStateDictionary'類型的第一個參數的擴展方法'AddModelError'(你是否缺少using指令或程序集引用?) – GlenCloncurry
使用'System.Web.Mvc.ModelStateDictionary.AddModelError'。 – mok