输入类型文件的验证在ASP.NET MVC 4中不起作用

时间:2013-12-06 09:51:44

标签: c# asp.net-mvc validation

我有以下型号:

 public class AModel
   {
      [ServerFileVerification( 1, FileType.TEST )]
      public HttpPostedFileBase[] Files
      {
         get;
         set;
      }
   }

属性:

public class ServerFileVerificationAttribute : RequiredAttribute 
{

   public ServerFileVerificationAttribute( ushort maximumNumberOfFiles, FileType fileType )
      {
         _maxFiles = maximumNumberOfFiles;
         _fileType = fileType;
      }

    public override bool IsValid( object value ) {
        HttpPostedFileBase[] files = value as HttpPostedFileBase[];
        string[] extensions = fileType == FileType.TEST ? {".zip"} : { ".txt" };

        foreach ( HttpPostedFileBase file in files ) {
           if(file == null ) continue;
           if ( !extensions.Contains( Path.GetExtension( file.FileName ) ) ) {
                     base.ErrorMessage = "The file " + file.FileName + " is invalid";
                     return false;
           }
        } 
    }
}

观点:

@using ( Html.BeginForm( "Test", "Test", FormMethod.Post, new { enctype = "multipart/form-data" } ) ) {

   for ( int i = 0; i < 5; i++ ) { 
      @Html.TextBoxFor( item => item.Files[i], new { type = "file" } );
      @Html.ValidationMessageFor( item => item.Files[i] )
      <br />
   }

   <input type="submit" />
}

控制器:

[HttpPost]
      public ActionResult Test( AModel model )
      {
         if ( ModelState.IsValid ) {
            return Redirect( "http://www.google.ro" );
         }

         return View( "Index", model );
      }

如果我上传除了ZIP以外的任何内容,那么应该显示错误,但它不会......

我的错误在哪里?我把ValidationMessageFor,但它不起作用......为什么?

2 个答案:

答案 0 :(得分:0)

像这样检查Controller中的ModelState

   if (ModelState.IsValid)
    {
       //Do the things that u want to do if there is no error  
    }
   else
    {
        return View("Create", Model);
    }

您将在页面中看到错误。

答案 1 :(得分:0)

检查ModelState中是否有错误的条目,是包含item.Files [i]或item.Files下列出的错误的密钥?我怀疑它应该是后者,在这种情况下代码应该是:

for ( int i = 0; i < 5; i++ ) { 
    @Html.TextBoxFor( item => item.Files[i], new { type = "file" } );
    <br />
}
@Html.ValidationMessageFor( item => item.Files ) //not Files[i]