MVC3----資料註解與驗證(1)

來源:互聯網
上載者:User

標籤: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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.