ASP.NET MVC- 数据验证机制
ASP.NET MVC的数据验证机制,比起ASP.NET WEBFORM那种高效很多。下面记录以下两个示例,以便日后方便查阅。
方式一:在Controller里通过AddModelError方法返回错误的验证信息,看一下代码示例:
Controller里的,注意看一下,他Add的时候提交是HTTPPOST,并且传参是传一个MODEL进来。
public ActionResult Add() { return View(); } [HttpPost] public ActionResult Add(Package.Model.Message message) { if (message.gName == null) { ModelState.AddModelError("gName", "姓名不能为空"); } if (message.gContent == null) { ModelState.AddModelError("gContent", "内容不能为空"); } if (ModelState.IsValid) { MessageDal msgDao = new MessageDal(); msgDao.Add(message); return View(); } return View(); } }
View里面的
@model Package.Model.Message @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Add</title> </head> <body> <div> @using (Html.BeginForm()) { @Html.ValidationSummary(true); <fieldset> <legend>我要留言</legend> <div> 留言名称:@Html.TextBoxFor(a => a.gName) @Html.ValidationMessageFor(a => a.gName) </div> <div> 留言内容:@Html.TextBoxFor(a => a.gContent) @Html.ValidationMessageFor(a => a.gContent) </div> <input type="submit" id="btnAdd" value="提交留言" /> </fieldset> } </div> </body> </html>
方式二:直接在MODEL层里添加上验证
如何把数据验证交给Model呢?这里需要引用一个DLL:System.ComponentModel.DataAnnotations
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Text; namespace Package.Model { /// <summary> /// Message:实体类(属性说明自动提取数据库字段的描述信息) /// </summary> [Serializable] public partial class Message { public Message() { } #region Model private int _id; private string _gname; private string _gcontent; public int Id { set { _id = value; } get { return _id; } } [DisplayName("姓名")] [Required(AllowEmptyStrings = false, ErrorMessage = "姓名不能为空")] public string gName { set { _gname = value; } get { return _gname; } } [Required(AllowEmptyStrings = false, ErrorMessage = "内容不能为空")] public string gContent { set { _gcontent = value; } get { return _gcontent; } } #endregion Model } }
更多在MODEL里验证的丰富示例:
namespace MvcApplication4.Models { public class UserInfo { //ID编号 [ScaffoldColumn(false)] [Required(AllowEmptyStrings = false, ErrorMessage = "用户ID不能为空")] [Display(Name = "记录编号", Order = 20000)] public int ID { get; set; } [Display(Order = 15000)] [Required(AllowEmptyStrings = false, ErrorMessage = "用户名不能为空")] [StringLength(20, MinimumLength = 6, ErrorMessage = "用户名不能大于{2} 且要小于{1}")] [Remote("User", "Validate", HttpMethod = "post", ErrorMessage = "用户名已经存在")] public string UserName { get; set; } [Display(Name="password")] [DataType(DataType.Password)] [Required(AllowEmptyStrings = false, ErrorMessage = "密码不能为空")] [StringLength(60, MinimumLength = 20, ErrorMessage = "密码必须在{2} 和{1}之间")] public string UserPassword { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "邮箱必填")] [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9]+\.[A-Za-z]{2,4}", ErrorMessage = "{0}的格式不正确")] public string Email { get; set; } [Compare("Email", ErrorMessage = "邮箱要相同")] public string TEmail { get; set; } //compare 大小写要相同 否则不会触发 验证 [Display(Name = "身份证号码")] [RegularExpression(@"\d{17}[\d|x]|\d{15}", ErrorMessage = "身份证号码格式错误")] public string IdentityNo { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "年龄必填")] [Range(10, 100, ErrorMessage = "年龄不能大于{2} 不能小于{1}")] public int Age { get; set; } [ReadOnly(true)] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")] [Required(ErrorMessage = "金额不能为空")] [Range(typeof(decimal), "20.0", "30.0", ErrorMessage = "金额在{1}和{2}之间")] public decimal Money { get; set; } } }
参考文章:http://www.cnblogs.com/jiagoushi/archive/2013/01/25/2876725.html