简体   繁体   English

在自定义ModelBinder中提取数据注释

[英]Extract Data Annotations in custom ModelBinder

I'm using a custom model binder in MVC that implements System.Web.Mvc.IModelBinder. 我在实现System.Web.Mvc.IModelBinder的MVC中使用自定义模型绑定程序。

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. 模型绑定器采用通用类型(类),提取每个类属性,并将这些属性以及有关每个属性的其他详细信息存储在List中。 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. 我想将它们存储为html属性,稍后可以在下面的示例中将其注入到用于显示属性的控件中。

<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? 如何将数据注释输出为html属性?

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. 为此,我实现了一个自定义的DataAnnotationsModelMetadataProvider(MpMetaDataProvider),我在MVC中注册并使用了它。 You register it in the Application_Start event of the Global.asax 您在Global.asax的Application_Start事件中注册它

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. 在我的MpMetaDataProvider中,我调用以下方法以返回特定类的特定属性的数据注释。 I hope this helps someone. 我希望这可以帮助别人。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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