Validation.IsValid() does not validate Error Razor C#

本文关键字:validate Error Razor not does IsValid Validation | 更新日期: 2023-09-27 17:58:31

我目前正在使用以下代码来验证上传的文件是否属于特定类型。然而,使用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>
            }
        }
    }

eddef

@FileUpload.GetHtml(
    initialNumberOfFiles:1,
    allowMoreFilesToBeAdded:false,
    includeFormTag:true,
    uploadText:"Upload CSV only")
@Html.ValidationMessage("fileUpload")

Validation.IsValid() does not validate Error Razor C#

试试这个

ModelState.AddModelError(string.Empty, "Only CSV are allowed"); 

而不是

ModelState.AddError("fileUpload", "Only CSV are allowed");

使用空键添加模型错误,而不是将其绑定到特定属性。
注意:通常最好将正确的属性添加到ViewModel中,并对该属性进行验证。