【转】MetadataType的使用,MVC的Model层数据验证
2011-07-08 10:08
706 查看
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();
}
指定要与数据模型类关联的元数据类
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();
}
相关文章推荐
- MetadataType的使用,MVC的Model层数据验证
- MetadataType的使用,MVC的Model层数据验证
- METADATATYPE的使用,MVC的MODEL层数据验证
- MetadataType的使用,MVC的Model层数据验证
- 【转】METADATATYPE的使用,MVC的MODEL层数据验证
- MVC使用jQuery从视图向控制器传递Model,数据验证,MVC HTML辅助方法小结
- MVC使用jQuery从视图向控制器传递Model,数据验证,MVC HTML辅助方法小结
- MVC使用jQuery从视图向控制器传递Model,数据验证,MVC HTML辅助方法小结
- Asp.net MVC 通过Attribute验证datamodel(二) ---使用IClientValidatable
- 解决使用Validform插件,datatype里用ajax验证数据是否已经存在时出现的问题
- MVC使用jQuery从视图向控制器传递Model,数据验证,MVC HTML辅助方法小结
- MVC 5使用TempData(对象)跨视图传递数据
- MVC数据验证使用小结
- DynamicData for Asp.net Mvc留言本实例 中篇 新建.删除.数据验证
- 【原创】Asp.Net MVC 学习笔记之-使用Model验证
- (JAVA SE 学习笔记)Java.SE.第003讲.原生数据类型使用陷阱.Pitfall.of.Primitive.Data.Type
- 第十节:数据批注(DataAnnotationModel)和自定义验证(包括Model级别的验证)
- Java SE 第三讲(原生数据类型使用陷阱 Pitfall of Primitive Data Type)
- 使用WebFrom来模拟一些MVC的MODEL与View的数据交互功能
- MVC验证12-使用DataAnnotationsExtensions对整型、邮件、最小值、文件类型、Url地址等验证