Extract Data Annotations in custom ModelBinder

人走茶凉 提交于 2019-12-23 03:42:20

问题


I’m using a custom model binder in MVC that implements System.Web.Mvc.IModelBinder.

The model binder takes a generic type (class) extracts each of the class properties and stores these in a List along with additional details about each property. For example for each Property it stores access permissions i.e. Read, Write, None for each property based on the logged in user. Then in my View I use this additional data to determine whether to display a specific property or not.

I want to be able to retrieve the validation data annotations attributes for each property and store these details also. I want to store them as html attributes that I can inject into the control used to display the property later like in the example below.

<input data-val="true" data-val-length="Address1&#32;must&#32;be&#32;less&#32;than&#32;8!!" data-val-length-max="8" data-val-required="Address&#32;Line&#32;1&#32;is&#32;required." id="Entity_Address_AddressLine1" name="Entity.Address.AddressLine1" type="text" value="aaaa1111" />

Do I have to use reflection to extract the data annotation attributes from the class or is there another method? How do I output the data annotations as html attributes?


回答1:


Here you go:

foreach (PropertyInfo prop in Model.GetType().GetProperties())
{
    var annotations = prop.GetCustomAttributes(typeof(ValidationAttribute), false);
    foreach(var annotation in annotations)
    {
        if(annotation is RequiredAttribute)
        {
            //...
        }
    }
}



回答2:


To do this I implemented a custom DataAnnotationsModelMetadataProvider (MpMetaDataProvider) which I registered and used in MVC. You register it in the Application_Start event of the Global.asax

ModelMetadataProviders.Current = new MpMetaDataProvider();

In my MpMetaDataProvider I call the below method to return the Data Annotations for a specific property of a specific class. I hope this helps someone.

this.GetMetadataForProperty(modelAccessor, modelProperty.Parent.EntityType, modelProperty.Name);


来源:https://stackoverflow.com/questions/20095424/extract-data-annotations-in-custom-modelbinder

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