MetadataType的使用,MVC的Model层数据验证
2013-11-14 18:08
519 查看
MetadataType的使用,MVC的Model层数据验证
指定要与数据模型类关联的元数据类
这样关联之后,可以做一些初始化的工作,还可以做一些验证,以及自定义的验证错误信息,相当于是扩展了Model实体
因为做验证都是在Model层做的,这样好维护,所以需要做元数据,与ADO.NET实体数据模型关联起来。
比如产品价格需要做个输入验证,怎么做呢,请看
对不对,是不是很好的进行了扩展,以后需要修改验证,只要在这个元数据类里面修改即可。
Controller层调用的时候,验证代码
指定要与数据模型类关联的元数据类
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辅助方法小结
- Asp.net MVC 通过Attribute验证datamodel(二) ---使用IClientValidatable
- 解决使用Validform插件,datatype里用ajax验证数据是否已经存在时出现的问题
- MVC使用jQuery从视图向控制器传递Model,数据验证,MVC HTML辅助方法小结
- MVC使用jQuery从视图向控制器传递Model,数据验证,MVC HTML辅助方法小结
- MVC数据验证原理及自定义ModelValidatorProvider实现无编译修改验证规则和错误信息
- 如何使用jQuery向asp.net Mvc传递复杂json数据-ModelBinder篇
- stream_get_meta_data 的使用方法及取得相关数据。
- JSP培训(7)——使用JDBC完成动态验证、采用MVC完成数据查询
- JSP培训(7)——使用JDBC完成动态验证、采用MVC完成数据查询
- asp.net MVC 中使用dataannotation验证Model
- MVC中如何使用Model验证
- MVC 强类型传值Model。和弱类型传值ViewData[""]。及用EF进行增删查改(母版页的使用)
- MVC 5使用ViewData(对象)显示数据