MVC中的自定义验证未在部分视图上执行 [英] Custom validation in MVC not executing on partial views

查看:90
本文介绍了MVC中的自定义验证未在部分视图上执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有文件上传的输入是强类型的,下面是 model类

So I have file uploading input which is strongly typed and below is the model class

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 链接单击的c $ c>:

and below is how I load partialview on click of a link:

$('#page-inner').empty().load('/Admin/GetMediaUploadView', function () {
      $.validator.unobtrusive.parse($('form#frmUploadImages'));
      //Apply client validation for partialviews
})

但是即使执行了所有步骤,它也不会显示任何消息,并且需要注意的是,如果我为同一属性添加 [Required] 属性,它会很好地工作,但是自定义验证我从未显示过任何消息。我还必须添加什么才能使此 CustomValidator 正常工作?我关注了 这篇文章 ,但仍无济于事。另外,如果有人让我知道如何更新此模型以便接受多张图像,那将有很大帮助。

But even after following all the steps, it isn't displaying any message and point to note is, if I add [Required] attribute for the same, it will work well, but custom validation what I have never displays any message. What else I have to add to make this CustomValidator to work? I followed this post but still could not be of much help. Also if anyone let me know how to update this model so as to accept multiple images, it will be of great help.

推荐答案

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

In order to get client side validation, your attribute must


  1. 实现 IClientValidatable 会添加关联到HTML的
    data-val-* 属性,并且

  2. 您必须包括脚本以向jQuery添加方法验证程序。

  1. implement IClientValidatable which will add the associated data-val-* attributes to you html, and
  2. you must include scripts to add methods to the jQuery validator.

本文是创建自定义客户端和服务器端验证属性的良好指南。

This article is a good guide to creating custom client and server side validation attributes.

还请注意,您的当前属性相当有限,因为文件类型和大小是固定的,并且包含属性以指定文件类型将更加灵活pes和最大文件大小,以便您可以将其用作(例如)

Note also your current attribute is rather limited in that the file types and size are fixed, and it would be more flexible to include properties to specify the file types and maximum file size so that you could use it as (say)

[FileValidation(MaxSize="1024", FileType="jpg|png")]
public HttpPostedFileBase Images { get; set; }

本文提供了一个示例示例,该属性可以验证文件类型,但可以对其进行修改包括 MaxSize 属性。

This article provide an example of an attribute that validates the file type, but could be adapted to include the MaxSize property.

侧面说明:如果加载动态内容,则应首先设置验证器到 null

Side note: If your loading dynamic content, then you should first set the validator to null

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

这篇关于MVC中的自定义验证未在部分视图上执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆