Asp.net mvc 添加“的最佳方式”;不同于;零验证属性
在ASP.NET MVC 3/4中添加“不同于零”验证属性的最佳方法是什么?我假设您希望添加带有错误消息“不同于零”的自定义验证属性(此处不确定正确的英语用法)。假设您有一个属性需要验证的模型:Asp.net mvc 添加“的最佳方式”;不同于;零验证属性,asp.net-mvc,validation,attributes,Asp.net Mvc,Validation,Attributes,在ASP.NET MVC 3/4中添加“不同于零”验证属性的最佳方法是什么?我假设您希望添加带有错误消息“不同于零”的自定义验证属性(此处不确定正确的英语用法)。假设您有一个属性需要验证的模型: public class YourModel { [Required] [CheckZero] //custom attribute public int PropertyName { get; set; } ... } 创建一个从ValidationAttrib
public class YourModel
{
[Required]
[CheckZero] //custom attribute
public int PropertyName { get; set; }
...
}
创建一个从ValidationAttribute
派生的类CheckZeroAttribute
,并重写基类提供的IsValid
方法之一。使用ValidationContext
参数覆盖IsValid
版本提供了在IsValid
方法中使用的更多信息(除其他信息外,ValidationContext
参数将允许您访问模型类型、模型对象实例和正在验证的属性的友好显示名称)
我想知道为什么我的问题是-1。。。
public class CheckZeroAttribute : ValidationAttribute
{
protected override ValidationResult IsValid (object value, ValidationContext validationContext)
{
//the error message
string sErrorMessage = "Different from zero";
//implement appropriate validation logic here
...
if (...) { return new ValidationResult(sErrorMessage); }
return ValidationResult.Success;
}
}