I'm using Data Annotations to validate my model classes. I wrote a couple of custom attributes as well. Ultimately, the model is pushed to a web interface built in ASP.NET MVC, but I want to keep a clean separation of concerns, so the model classes has its own assembly (which will also be used by console apps). Having to use the IClientValidatable
interface (which is a web concern) in the model layer breaks the loose coupling I'm aiming for. Any ideas on how to fix this? Thanks.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can add adapter for data annotation attribute.
For example you have MyValidationAttribute.
You need add adapter like following:
public class MyValidationAttributeAdapter : DataAnnotationsModelValidator<MyValidationAttribute>
{
public MyValidationAttributeAdapter(ModelMetadata metadata, ControllerContext context, MyValidationAttribute attribute) : base(metadata, context, attribute)
{
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
//return client rule here
return base.GetClientValidationRules();
}
}
And somewhere on application start add code, which register this adapter:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyValidationAttribute), typeof(MyValidationAttributeAdapter));