我正在创建一个MVC 3应用程序,需要根据外部数据(例如:Required、MinimumLength、MaximumLength等)在运行时建立数据验证规则。在MVC 3中使用Data Annotations似乎很自然,但是提供验证元数据的属性特性是在编译时设置的。
是否有一种模式可以在运行时使用提供的元数据来使用Data Annotations?
示例:
public string Text { get; set; }
public void SetIsRequired(string propertyName, bool required)
{
// Somehow find the property 'propertyName' and create/remove a RequiredAttribute
// on that property
}
...
SetIsRequired("Text", true);
我知道TypeDescriptor,但是没有找到可以修改实例属性的属性选项(只有类级别的实例属性或类型属性级别的属性)。
FluentValidation.MVC3
NuGet,注册流畅验证模型验证器提供程序在您的Application_Start中:FluentValidationModelValidatorProvider.Configure();
然后您就可以为您的模型定义验证器了。 - Darin Dimitrov