Keeping IClientValidatable outside the model layer

安稳与你 提交于 2019-12-11 05:41:14

问题


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));


来源:https://stackoverflow.com/questions/19639752/keeping-iclientvalidatable-outside-the-model-layer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!