我在实现自定义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; }