=======================验证注解的使用
需要引用名称空间:
using System.ComponentModel.DataAnnotations;
--------------Required(不允许为空)
案例:
--模型代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace MvcApplication3.Models { public class SchoolType { [Key] public virtual int st_id { get; set; } [Required] //不许为空 [StringLength(10)] //字符串的最大长度 [DataType (DataType.MultilineText)] //多行文本模式 public virtual string st_name{get;set;} public virtual List<School> Schools { get; set; } } }
--控制器代码:
[HttpPost] public ActionResult TestModel(SchoolType st) { if (ModelState.IsValid) { db.Entry(st).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(db.SchoolTypes.Single(r => r.st_id == 1)); }
--视图代码:
@{ ViewBag.Title = "TestModel"; } <h2>TestModel</h2> @using(Html.BeginForm()) { <br /> @Html.EditorForModel() <input type="submit" value="提交" /> }
--------------StringLength(字符串长度验证,用法如上)
[StringLength(10)]:最大字符串10
[StringLength(10,MinimumLength=3)]:最小字符串长度3最大字符串10
--------------RegularExpression(正则表达式验证)
[RegularExpression(@"[a-z][A-Z]")]
--------------Range(范围验证)
[Range(10,20)]:最小值10,最大值20
[Range(typeof(decimal), "0.00", "10.01")]:小数范围
[Range(typeof(DateTime), "2015-1-5 10:59:04", "2015-1-5 13:59:09")]:时间范围
时间: 2024-10-12 19:12:09