zoukankan      html  css  js  c++  java
  • 使用DataAnnotations实现数据验证

     

    System.ComponentModel.DataAnnotations命名空间中有一些特性类(如Required,Range),可以用来实现数据验证功能。

    使用时先在文件头部引入命名空间:

     using System.ComponentModel.DataAnnotations;

    namespace Test

    {

      public class User

      {

         [Required] 

         public int UserId{set; get;}

     

        [Range(1,200,ErrorMessage="年龄超出范围")]

        public int Age(set; get;} 

      } 

     

    此外,在使用了实体框架EF自动生成了类后,如果要使用DataAnnotations中的特性类,可以使用在分部类中添加内部元数据类型的方法来实现(假设EF已经自动创建了分部User类): 

    新建==>,命名为User,然后改成分部类:为类添加MetadataType特性,并在类中添加一个内部类  //注意:两个User类必须在同一个命名空间中!!!

     using System.ComponentModel.DataAnnotations;

    namespace Test

    {

      [MetadataType(typeof(UserMD))]  //类名UserMD随便起,但需要和后面一致

      public particial class User

      {

        public class UserMD

      { 

         [Required] 

         public int UserId{set; get;}

     

        [Range(1,200,ErrorMessage="年龄超出范围")]

        public int Age(set; get;} 

       } 

      } 

     

  • 相关阅读:
    NodeJS、NPM安装配置步骤(windows版本)
    23种设计模式全解析
    js阻止浏览器默认事件
    js获取不同浏览器盒子宽度高度
    H5之重力感应篇
    JS中的call()和apply()方法
    html学习笔记
    less(css)语言快速入门
    power designer简单教程
    Strom开发配置手册
  • 原文地址:https://www.cnblogs.com/lgzslf/p/2127409.html
Copyright © 2011-2022 走看看