文件上传,客户端脚本未调用?资料注解 [英] File upload, Client script not called ? Data-annotation

查看:63
本文介绍了文件上传,客户端脚本未调用?资料注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC Web应用程序中,我有一个带有imageupload组件的表单. imageupload图像数据在数据注释的帮助下进行了验证. 我的服务器端验证工作正常,但是未调用我的客户端jQuery函数...我不知道为什么-帮助:

In my MVC web application, I have a form with a imageupload component. The imageupload Image-data is validated with help of data-annotation. My server side validation is WORKING, but my client side jQuery function is not being called ... I don't know why- HELP:

1.在我的视图中上传文件:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")

<input type="file" id="FileUploader" name="FileUploader" multiple />
<div id="FileDisplay" name="FileDisplay"></div>
@Html.ValidationMessageFor(model => model.FileUploader, "", new { @class = "text-danger" })

2.在我的模型中,我有这个:

[ValidImageUpload]
public IEnumerable<HttpPostedFileBase> FileUploader { get; set; }

3.ValidImageUpload文件:

public sealed class ValidImageUpload : ValidationAttribute, IClientValidatable
{
    string[] stringArray = { "gif", "jpg", "png", "jpeg" };

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        IEnumerable<System.Web.HttpPostedFileBase> uploadedFiles = (IEnumerable<System.Web.HttpPostedFileBase>)value;
        var firstfile = uploadedFiles.FirstOrDefault();

        if (firstfile != null)
        {
            foreach (var file in uploadedFiles)
            {
                int pos = Array.IndexOf(stringArray, file.ContentType.Substring(6));

                if (pos > -1)
                {
                    if (file.ContentLength > 5242880)
                    {
                        return new ValidationResult(String.Format("Billedet: {0} er for stort. (Max. tilladt billede-størrelse xxxxx)", file.FileName));
                    }
                }
                else
                {
                    return new ValidationResult(String.Format("Billedt: {0} har et forkert format. Tilladte formater er - GIF, JPG, PNG, JPEG", file.FileName));
                }
            }
        }
        return ValidationResult.Success; 
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        ModelClientValidationRule mvr = new ModelClientValidationRule();
        mvr.ErrorMessage = "Forkert format";
        mvr.ValidationType = "validImageUpload";
        return new[] { mvr };
    }
}

jQuery

$(document).ready(function () {
    jQuery.validator.addMethod('validImageUpload', function (value, element, params) {
        var currentDate = new Date();
        alert('Working indsi´side');
            return false;

    }, '');

    jQuery.validator.unobtrusive.adapters.add('validImageUpload', function (options) {
        options.rules['validImageUpload'] = {};
        options.messages['validImageUpload'] = options.message;
    });
});

推荐答案

未获得任何客户端验证的原因是,您尚未在html中添加适当的data-val-*属性.始终使用强类型的HtmlHelper方法来生成您的html

The reason you do not get any client side validation is because you have not added the appropriate data-val-* attributes in your html. Always use the strongly typed HtmlHelper methods to generate your html, in your case

@Html.TextBoxFor(m => m.FileUploader, new { type="file", multiple="multiple"})

在内部,该方法从验证属性读取元数据,并将适当的属性添加到html.首次呈现页面时,jquery.validate.unobtrusive.js文件读取这些属性的值,并将规则添加到jquery.valdate.js中以进行客户端验证.

Internally the method reads the metatdata from the validation attributes and adds the appropriate attributes to the html. When the page is first rendered, the jquery.validate.unobtrusive.js file reads the values of those attributes and adds the rules to jquery.valdate.js for client side validation.

不过,您的实现还有其他多个问题.您要验证2个独立的内容-文件大小和文件类型-因此您需要2个独立的属性.而且您的属性是不灵活的,因为您已经将有效值硬编码到了代码中(您将不得不重复所有代码以将其应用于另一个只允许说.pdf文件的属性).您也不会在GetClientValidationRules()方法中返回任何参数来指示有效的文件类型(或文件大小).并且javascript函数不应位于document.ready()之内.

However there are multiple other issues with you implementation. Your validating 2 separate things - the file size and the file type - so you need 2 separate attributes. And your attribute is inflexible because you have hard coded the valid values into the code (you would have to repeat all the code to apply it to another property where you only wanted to allow say .pdf files). Your also not returning any parameters in the GetClientValidationRules() method to indicate what file types (or file size) is valid. And the javascript functions should not be inside document.ready().

有关FileTypeAttribute的实现,请参考在ASP.NET MVC中进行客户端文件上传大小验证(请注意,该解决方案适用于单个文件,并且需要修改才能上传多个文件).

For an implementation of a FileTypeAttribute, refer FileExtension Validation using custom validation creates duplicate and invalid data-* attributes. And for an implementation of a FileSizeAttribute, refer Client-side File Upload Size Validation in ASP.NET MVC (note that that solution is for a single file and would need to be modified for uploading multiple files).

我还建议您进行研究 查看全文

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