標籤:public 空間 模型
=======================驗證註解的使用
需要引用名稱空間:
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(Regex驗證)
[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")]:時間範圍
本文出自 “程式猿的家--Hunter” 部落格,請務必保留此出處http://962410314.blog.51cto.com/7563109/1601232
MVC3----資料註解與驗證(1)