• MetadataType的使用,MVC的Model层数据验证


    //ActivityFlowContent是实体模型的model类  

    //ActivityFlowContentMetadata是自己写的model类

    //这两个类属性相同可以形成映射关系,ActivityFlowContent中还可以加其他额外字段

    [MetadataType(typeof(ActivityFlowContentMetadata))]

        public partial class ActivityFlowContent : IBaseEntity
        {
            
            [Display(Name = "活动流程分类")]
            public string ActivityClassificIDOld { get; set; }
            
            #region 自定义属性

            #endregion

        }
        public class ActivityFlowContentMetadata
        {
                [ScaffoldColumn(false)]
                [Display(Name = "主键", Order = 1)]
                public string ID { get; set; }

                [ScaffoldColumn(true)]
                [StringLength(36, ErrorMessage = "长度不可超过36")]
                [Display(Name = "活动分类ID", Order = 2)]
                public object ActivityClassificID { get; set; }

                [ScaffoldColumn(true)]
                [StringLength(200, ErrorMessage = "长度不可超过200")]
                [Display(Name = "活动摘要", Order = 3)]
                public object Sumary { get; set; }

                [ScaffoldColumn(true)]
                [DataType(DataType.MultilineText,ErrorMessage="字符格式不正确")]
                [Display(Name = "活动内容", Order = 4)]
                public object Content { get; set; }

                [ScaffoldColumn(true)]
                [StringLength(50, ErrorMessage = "长度不可超过50")]
                [Display(Name = "关键字", Order = 5)]
                public object Keywords { get; set; }


        }
     
     

    MetadataType的使用,MVC的Model层数据验证
    指定要与数据模型类关联的元数据类

    using System.ComponentModel.DataAnnotations;

     //指定要与数据模型类关联的元数据类
        [MetadataType(typeof(Product_MetaData))]
        public partial class Product
        {
            public Product()
            {
                this.ProductGuid = Guid.NewGuid();
                this.AddTime = DateTime.Now;
            }
            public class Product_MetaData
            {
                public Guid ProductGuid { get; set; }
                [Required(ErrorMessage = "产品名称不能为空")]
                public string ProductName { get; set; }
                public DateTime AddTime { get; set; }
            }
        }

    这样关联之后,可以做一些初始化的工作,还可以做一些验证,以及自定义的验证错误信息,相当于是扩展了Model实体
    因为做验证都是在Model层做的,这样好维护,所以需要做元数据,与ADO.NET实体数据模型关联起来。
    比如产品价格需要做个输入验证,怎么做呢,请看
    [RegularExpression(@"^(d+)(.d+)?", ErrorMessage = "价格格式错误")]
    [Required(ErrorMessage = "*")]
    public double ProductPrice { get; set; }
    对不对,是不是很好的进行了扩展,以后需要修改验证,只要在这个元数据类里面修改即可。

    Controller层调用的时候,验证代码
    if (!ModelState.IsValid)
    {
     return View();

    }
     
     
  • 相关阅读:
    一、redis的简介与安装
    三、Mybatis全局配置文件说明
    第七章、本地方法栈
    第六章、本地方法接口
    二、MyBatis接口开发
    第五章、虚拟机栈
    一、Mybatis入门
    第八章、声明式事务管理
    第七章、JdbcTemplate
    第六章、以XML方式配置切面
  • 原文地址:https://www.cnblogs.com/Alex80/p/5145808.html
Copyright © 2020-2023  润新知