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.

有帮助吗?

解决方案

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));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top