简体   繁体   中英

Extract Data Annotations in custom ModelBinder

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 ie 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?

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)
        {
            //...
        }
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM