提取数据批注自定义模型绑定器 [英] Extract Data Annotations in custom ModelBinder

查看:132
本文介绍了提取数据批注自定义模型绑定器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVC中的自定义模型绑定实现System.Web.Mvc.IModelBinder。

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.

我希望能够检索验证数据的注释为每个属性的属性和存储这些细节也。我想并将其作为HTML属性,我可以注入到以后使用像在下面的例子中显示属性的控制。

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" />

我必须使用反射来提取数据注解从类属性还是有其他方法?我如何输出数据注解的HTML属性?

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?

推荐答案

在这里你去:

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

这篇关于提取数据批注自定义模型绑定器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆