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

Data Annotation的更多相关文章

  1. Data Validate 之 Data Annotation

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

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

    Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc5-ef6-bs3-get-started-server-side-validation.html 系列 ...

  3. 在@Data注释lombok上使用继承警告等于/ hashCode(Warning equals/hashCode on @Data annotation lombok with inheritance)

    生成equals / hashCode实现但没有调用超类,即使这个类没有扩展java.lang.Object.如果这是故意的,请将 @EqualsAndHashCode(callSuper = fal ...

  4. Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 创建复杂数据模型

    Creating a complex data model 创建复杂数据模型 8 of 9 people found this helpful The Contoso University sampl ...

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

    spring data mongodb中,如果对象中的属性不想加入到数据库字段中,可加@Transient注解,声明为透明属性 spring data mongodb 官网帮助文档 http://ww ...

  6. 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 S ...

  7. Spring Data Elasticsearch

    项目清单   elasticsearch服务下载包括其中插件和分词   http://download.csdn.net/detail/u014201191/8809619   项目源码   资源文件 ...

  8. WPF中使用Data Annotations验证Model

    .NET Framework中System.ComponentModel.DataAnnotations提供了很多属性来验证对象的属性.可以在C:\Program Files (x86)\Refere ...

  9. Spring Data 整合 ElasticSearch搜索服务器

    一.基于 maven 导入坐标(pom.xml文件) <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi ...

随机推荐

  1. [Swust OJ 795]--Penney Game

    题目链接:http://acm.swust.edu.cn/problem/795/ Time limit(ms): 1000 Memory limit(kb): 65535   Description ...

  2. JDK和JRE的差异和区别

    来源:http://docs.oracle.com/javase/7/docs/

  3. 项目中js调用service和procedure的办法

    Ajax.js /**通用ajax服务的定义对象 * services可以是单个服务对象,也可以是service服务数组 * 具体服务的定义请参考appendServices成员函数 */ funct ...

  4. [LeetCode]题解(python):027-Remove Element

    题目来源: https://leetcode.com/problems/remove-element/ 题意分析: 给定一个数组和一个数值val,将数组中数值等于val的数去除.不能申请额外空间,超过 ...

  5. C语言选择法排序

    #include <stdio.h> int main() { int i, j, p, n, q; ] = {, , , , }; //对无序数组进行排序 ; i<; i++) { ...

  6. cocos2dx进阶学习之CCTMXTiledMap

    继承关系 CCTMXTiledMap -> CCNode 它由CCNode派生,我们已经知道CCNode是cocos2dx的舞台对象的公共父类,所以CCTMXTiledMap也是个舞台对象 成员 ...

  7. C# 操作Excel (二)

    根据翻阅LTP.Net知识库系列之四中Office操作功能: 一.记录常用如下 (1)“在自己的程序中宿主Office”的意思就是在我们自己开发的应用程序的窗体上,显示一个就像Office应用程序那样 ...

  8. Poj 1002 487-3279(二叉搜索树)

    题目链接:http://poj.org/problem?id=1002 思路分析:先对输入字符进行处理,转换为标准形式:插入标准形式的电话号码到查找树中,若有相同号码计数器增加1,再中序遍历查找树. ...

  9. Courses(最大匹配)

    Courses Time Limit: 20000/10000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total S ...

  10. 读懂Swift 2.0中字符串设计思路的改变

    Swift提供了一种高性能的,兼容Unicode编码的String实现作为标准库的一部分.在 Swift2中,String类型不再遵守CollectionType协议.在以前,String类型是字符的 ...