0

我在实现ValidationAttribute需要客户端和服务器验证的自定义时遇到问题。当严格在服务器上运行时,它会按预期通过和失败验证,但错误消息不会发送回客户端。在客户端一切正常。

属性

public class MaxFileSizeAttribute : ValidationAttribute, IClientValidatable
{
    private int _maxFileSize;

    public MaxFileSizeAttribute(int maxFileSize)
    {
        _maxFileSize = maxFileSize;
    }

    public override bool IsValid(object value)
    {
        HttpPostedFileBase file = value as HttpPostedFileBase;

        if (file == null)
        {
            return false;
        }

        return file.ContentLength <= _maxFileSize;
    }

    public override string FormatErrorMessage(string name)
    {
        return base.FormatErrorMessage(_maxFileSize.ToString());
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(_maxFileSize.ToString()),
            ValidationType = "filesize"
        };
        rule.ValidationParameters["maxsize"] = _maxFileSize;
        yield return rule;
    }
}

该视图包括:

    @Html.ValidationMessageFor(model => model.File)
    @Html.TextBoxFor(model => model.File, new { type="file", style="width:79%", placeholder="Select CSV or TXT file for upload"})

以及 ViewModel 的相关部分

    [MaxFileSize(10 * 1024 * 1024, ErrorMessage="File size must be less than 10mb")]
    public HttpPostedFileBase File { get; set; }
4

0 回答 0