C# 自定义ValidationAttribute按预期执行验证,但在服务器上验证时不显示错误消息
我在实现自定义C# 自定义ValidationAttribute按预期执行验证,但在服务器上验证时不显示错误消息,c#,asp.net-mvc,C#,Asp.net Mvc,我在实现自定义ValidationAttribute时遇到问题,该属性需要客户端和服务器验证。当严格在服务器上运行时,它会按预期通过并失败验证,但不会将错误消息发送回客户端。在客户机上一切正常 属性 public class MaxFileSizeAttribute : ValidationAttribute, IClientValidatable { private int _maxFileSize; public MaxFileSizeAttribute(int maxFi
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;
}
}
以及ViewModel的相关部分
[MaxFileSize(10 * 1024 * 1024, ErrorMessage="File size must be less than 10mb")]
public HttpPostedFileBase File { get; set; }
你确定你一步一步地遵循了我在这里描述的一切吗?因为我的代码工作得很好,并且显示了正确的错误消息。显然不是,在更改控制器的返回值后,它似乎要好一点。我现在遇到了一个问题,在第一次加载页面时会立即调用它(即,我在按下任何键之前收到验证消息);是的,这是一步一步的
[MaxFileSize(10 * 1024 * 1024, ErrorMessage="File size must be less than 10mb")]
public HttpPostedFileBase File { get; set; }