문제

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