我正在使用DataAnnotation
Attributes 在 MVC 之外对我的模型上的属性应用验证。
public class MyModel
{
[Required]
[CustomValidation]
public string Foo { get; set; }
}
我已经实现了以下扩展方法来验证模型。
public static void Validate(this object source)
{
if (source == null)
throw new ArgumentNullException("source");
var results = new List<ValidationResult>();
bool IsValid = Validator.TryValidateObject(source, new ValidationContext(source, null, null), results, true);
if (!IsValid)
results.ForEach(r => { throw new ArgumentOutOfRangeException(r.ErrorMessage); });
}
Validate()
每次设置不方便的属性时,我都必须调用此方法:
MyModel model = new MyModel();
model.Foo = "bar";
model.Validate();
model.Foo = SomeMethod();
model.Validate();
我希望Validate()
在模型状态发生变化时在幕后自动调用该方法。有人对如何实现这一目标有任何想法吗?
对于奖励积分,有人知道 MVC 是如何通过 实现这种自动验证的DataAnnotations
吗?
谢谢。