C# MVC中的自定义验证未在局部视图上执行

C# MVC中的自定义验证未在局部视图上执行,c#,asp.net-mvc,asp.net-mvc-4,custom-validators,C#,Asp.net Mvc,Asp.net Mvc 4,Custom Validators,因此,我有文件上传输入,它是强类型的,下面是模型类 public class UploadImageAlbum { [CustomFileValidator] public HttpPostedFileBase Images { get; set; } } 我的CustomFileValidator类如下: [AttributeUsage(AttributeTargets.Property,AllowMultiple =true,Inherited =false)] publi

因此,我有文件上传输入,它是强类型的,下面是
模型类

public class UploadImageAlbum
{
    [CustomFileValidator]
    public HttpPostedFileBase Images { get; set; }
}
我的
CustomFileValidator
类如下:

[AttributeUsage(AttributeTargets.Property,AllowMultiple =true,Inherited =false)]
public class CustomFileValidator : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        const int maxContent = 1024 * 1024 * 50;//50 MB
        var sAllowedExt = new string[] { ".jpg", ".png" };
        var file = value as HttpPostedFileBase;
        //Check for null
        if (file == null)
        {
            return new ValidationResult("Please select an image to upload");
        }

        //Check for File Extension
        if (sAllowedExt.ToList().Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
        {
            return new ValidationResult("Please Upload a valid file of type : " + string.Join(",", sAllowedExt));
        }

        //Check for length of file
        if(file.ContentLength>maxContent)
        {
            return new ValidationResult("File is too large, maximum allowed size is :" + (maxContent / 1024) + "MB");
        }
        return ValidationResult.Success;
    }
}
@using (Html.BeginForm("UploadImages", "Admin", FormMethod.Post, htmlAttributes: new { id = "frmUploadImages", novalidate = "novalidate", autocomplete = "off", enctype = "multipart/form-data" }))
{
      <div class="form-group">
            <span class="btn btn-default btn-file-img">
                  Browse @Html.TextBoxFor(m => m.UIAModel.Images, new { type = "file", multiple = "multiple", data_charset = "file" })
            </span>&nbsp;
            <span class="text-muted" id="filePlaceHolder">No files selected</span>
            @Html.ValidationMessageFor(m=>m.UIAModel.Images, null, htmlAttributes: new { @class = "invalid" })
      </div>
      <div class="form-group">
         <button class="btn btn-primary addImage pull-right">
             <i class="fa fa-upload"></i> Upload
         </button>
      </div>
}
我的
partialview
如下:

[AttributeUsage(AttributeTargets.Property,AllowMultiple =true,Inherited =false)]
public class CustomFileValidator : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        const int maxContent = 1024 * 1024 * 50;//50 MB
        var sAllowedExt = new string[] { ".jpg", ".png" };
        var file = value as HttpPostedFileBase;
        //Check for null
        if (file == null)
        {
            return new ValidationResult("Please select an image to upload");
        }

        //Check for File Extension
        if (sAllowedExt.ToList().Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
        {
            return new ValidationResult("Please Upload a valid file of type : " + string.Join(",", sAllowedExt));
        }

        //Check for length of file
        if(file.ContentLength>maxContent)
        {
            return new ValidationResult("File is too large, maximum allowed size is :" + (maxContent / 1024) + "MB");
        }
        return ValidationResult.Success;
    }
}
@using (Html.BeginForm("UploadImages", "Admin", FormMethod.Post, htmlAttributes: new { id = "frmUploadImages", novalidate = "novalidate", autocomplete = "off", enctype = "multipart/form-data" }))
{
      <div class="form-group">
            <span class="btn btn-default btn-file-img">
                  Browse @Html.TextBoxFor(m => m.UIAModel.Images, new { type = "file", multiple = "multiple", data_charset = "file" })
            </span>&nbsp;
            <span class="text-muted" id="filePlaceHolder">No files selected</span>
            @Html.ValidationMessageFor(m=>m.UIAModel.Images, null, htmlAttributes: new { @class = "invalid" })
      </div>
      <div class="form-group">
         <button class="btn btn-primary addImage pull-right">
             <i class="fa fa-upload"></i> Upload
         </button>
      </div>
}

但是,即使完成了所有步骤,它也不会显示任何消息,值得注意的是,如果我为相同的内容添加
[Required]
属性,它会工作得很好,但自定义验证我从未显示过任何消息。要使这个
CustomValidator
正常工作,我还需要添加什么?我跟着,但还是帮不了什么忙。另外,如果有人告诉我如何更新此
模型
,以便接受多个图像,这将非常有帮助。

为了获得客户端验证,您的属性必须

  • 实现将添加关联的
    data val-*
    属性,以及
  • 您必须包含向jQuery验证程序添加方法的脚本
  • 是创建自定义客户端和服务器端验证属性的良好指南

    还要注意的是,您当前的属性相当有限,因为文件类型和大小是固定的,如果包含属性来指定文件类型和最大文件大小,那么您可以将其用作(例如)

    提供一个属性示例,该属性验证文件类型,但可以修改为包含
    MaxSize
    属性

    旁注:如果您正在加载动态内容,则应首先将验证器设置为
    null

    var form = $('form#frmUploadImages');
    form.data('validator', null);
    $.validator.unobtrusive.parse(form);
    

    否决票??是否至少删除一条评论…:/是否需要客户端验证?您的属性未实现客户端验证所需的
    iclientvalidable
    。您还需要一个脚本来向jquery.validate添加方法/规则。请参阅StephenMuecke的指南。。它就在我上面链接的帖子里,但没有太多解释。。谢谢你……)如果您将其作为答案发布,并进行一些修改或解释,那么我将接受它:)这是如此方便,现在我明白了这种形式的验证。感谢您简单而简洁的解释:)