Data Annotation

Data Annotation

  1. 什么是Data Annotation ?
  2. 如何使用 ?
  3. 自定义Validate Attribute
  4. EF  Db first中使用Data Annotation
  5. asp.net MVC中使用Data Annotation

什么是Data Annotation ?

貌似没听过,但肯定见过

所属程序集:System.ComponentModel.DataAnnotations

DataAnnotation code:

  public class Product
    {

        [Required]
        [StringLength(10,MinimumLength =5)]
        public string Name { get; set; }

        [Required]
        public decimal? UnitPrice { get; set; }
    }

没错,就是给类的属性加上描述性的验证信息,

如何使用这些信息 为我们自己所用呢?

当然是先自己想办法了,

添加辅助类:

    public class ModelValidationError
    {
        public string FieldName { get; set; }
        public string Message { get; set; }
    }
    public static class DataAnnotationHelper
    {
        public static IEnumerable<ModelValidationError> IsValid<T>(this T o)
        {
            var descriptor = GetTypeDescriptor(typeof(T));

            foreach (PropertyDescriptor propertyDescriptor in descriptor.GetProperties())
            {
                var validations = propertyDescriptor.Attributes.OfType<ValidationAttribute>();
                foreach (var validationAttribute in validations)
                {
                    var v = propertyDescriptor.GetValue(o);

                    if (!validationAttribute.IsValid(v))
                    {
                        yield return new ModelValidationError() { FieldName = propertyDescriptor.Name, Message = validationAttribute.FormatErrorMessage(propertyDescriptor.Name) };
                    }
                }
            }
        }
        private static ICustomTypeDescriptor GetTypeDescriptor(Type type)
        {
            return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);
        }
    }

如何使用:

 class Program
    {
        static void Main(string[] args)
        {
            Product product = new Product();
            foreach (var item in product.IsValid())
            {
                Console.WriteLine("FieldName:{0} Error Message:{1}", item.FieldName, item.Message);
            }
            Console.ReadKey();
        }
    }

自定义ValidateAttribute

.net 提供的 ValidateAttribute不够用怎么搞?自定义呗,

    public class PriceAttribute : ValidationAttribute
    {
        public double MinPrice { get; set; } 

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return false;
            }
            var price = (double)value;

            if (price < MinPrice)
            {
                return false;
            }
            return true;
        }
        public override string FormatErrorMessage(string name)
        {
            return "Min Price is "+MinPrice;
        }
    }

使用方法和.net 提供的一样:

    public class Product
    {

        [Required]
        [StringLength(10,MinimumLength =5)]
        public string Name { get; set; }

        [Required]
        [Price(MinPrice =2)]
        public decimal? UnitPrice { get; set; }
    }

EF  Db first中使用Data Annotation

实际应用中遇到的问题:

在使用EF DBfirst的时候,实体类的validate attribute,一不小心经常会被覆盖掉,如何解决

巧妙使用partial 类

    public class ProductMetaData
    {
        [Required]
        [StringLength(10, MinimumLength = 5)]
        public string Name { get; set; }

        [Required]
        [Price(MinPrice = 2)]
        public decimal? UnitPrice { get; set; }
    }
    [MetadataType(typeof(ProductMetaData))]
    public partial class Product
    {

    }
    public partial class Product
    {
        public string Name { get; set; }

        public decimal? UnitPrice { get; set; }
    }

asp.net mvc 中data annotation的使用:

asp.net mvc中对data annotation具有原生的支持,

默认情况下,ASP.NET MVC框架在模型绑定时执行验证逻辑。

模型邦定器一旦完成对模型属性的更新,就会利用当前的模型元数据获得模型的所有验证器。这运行时提供了一个验证其 (DataAnnotationModelValidator)来与注解一同工作。这个模型验证器会找到所有的验证特性并执行它们包含的验证逻辑。 ModelBinder捕获所有失败的验证其规则并把它们放入ModelState中。

模型绑定的主要产物就是ModelState(Controller的属性)。

这个对象不仅包含了用户所有想放入模型属性里的值,也包括与每一个属性相关联的所有错误,和模型本身的错误,如果存在错误ModelState.IsValid返回false。

ModelState("LastName").Errors[0].ErrorMessage;//查看LastName属性的错误信息

View中查看:@Html.ValadationMessageFor(m=>m.LastName)

在编辑操作的PostAction中,可以先使用ModelState.IsValid属性判断是否通过验证,再不同对待。

参考文档:

http://www.asp.net/mvc/overview/older-versions-1/models-data/validation-with-the-data-annotation-validators-cs

http://www.cnblogs.com/xinchuang/archive/2013/06/06/3120482.html

http://www.cnblogs.com/kevin-kingdom/archive/2012/12/07/2807138.html

http://www.cnblogs.com/hjf1223/archive/2010/11/07/independent-dataannotation-validation.html

时间: 2024-07-29 14:34:02

Data Annotation的相关文章

MVC5 + EF6 + Bootstrap3 (15) 应用ModelState和Data Annotation做服务器端数据验证

Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc5-ef6-bs3-get-started-server-side-validation.html 系列教程:MVC5 + EF6 + Bootstrap3 上一节:MVC5 + EF6 + Bootstrap3 (14) 分部视图PartialView 源码下载:点我下载 目录 前言 通过ModelState验证数据 通过Data Annotation验证数据 结尾 前言 在提交数据前进行数据验证可

Data Validate 之 Data Annotation

什么是Data Annotation ? 如何使用 ? 自定义Validate Attribute EF  Db first中使用Data Annotation asp.net MVC中使用Data Annotation 什么是Data Annotation ? 貌似没听过,但肯定见过 所属程序集:System.ComponentModel.DataAnnotations DataAnnotation code: public class Product { [Required] [String

Spring Data Elasticsearch

项目清单 elasticsearch服务下载包括其中插件和分词 http://download.csdn.net/detail/u014201191/8809619 项目源码 资源文件 app.properties [java] view plain copy print? elasticsearch.esNodes=localhost:9300 elasticsearch.cluster.name=heroscluster app.xml [java] view plain copy prin

Spring Data MongoDB实战(上)

Spring Data MongoDB实战(上) 作者:chszs,版权所有,未经同意,不得转载.博主主页:http://blog.csdn.net/chszs 本文会详细展示Spring Data MongoDB是如何访问MongoDB数据库的.MongoDB是一个开源的文档型NoSQL数据库,而Spring Data MongoDB是Spring Data的模块之一,专用于访问MongoDB数据库.Spring Data MongoDB模块既提供了基于方法名的查询方式,也提供了基于注释的查询

[Spring Data MongoDB]学习笔记--_id和类型映射

_id字段的映射: MongoDB要求所有的document都要有一个_id的字段. 如果我们在使用中没有传入_id字段,它会自己创建一个ObjectId. { "_id" : ObjectId("53e0ff0b0364cb4a98ce3bfd"), "_class" : "org.springframework.data.mongodb.examples.hello.domain.Person", "name&q

Create the Data Access Layer

https://docs.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/create_the_data_access_layer This tutorial describes how to create, access, and review data from a database using ASP.NET Web Forms an

Spring Data MongoDB example with Spring MVC 3.2

Spring Data MongoDB example with Spring MVC 3.2 Here is another example web application built with Spring MVC 3.2 and Spring Data 1.2, integrating with the MongoDB document database. STEP 1: Create new webapp project, I will use maven for this. (Note

spring data mongodb中,如果对象中的属性不想加入到数据库字段中

spring data mongodb中,如果对象中的属性不想加入到数据库字段中,可加@Transient注解,声明为透明属性 spring data mongodb 官网帮助文档 http://www.boyunjian.com/javadoc/org.springframework.data/spring-data-mongodb/1.2.3.RELEASE/_/org/springframework/data/mongodb/core/query/Criteria.html#all(jav

使用JAVA操作ElasticSearch(Java API 和Spring Data ElasticSearch)

Java API 我的ElasticSearch集群的版本是6.2.4,导入elasticsearch相关的maven依赖也是6.2.4,不同版本的api可能会有差异 一:maven依赖 <!--elasticsearch核心依赖--> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version