MVC中的驗證規則

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   os   sp   for   on   

 

 前面的部落格中曾經提到過ModelBing機制,也在Demo中體現過,在MVC中更吊的是封裝了自訂的驗證規則。下面來一個Demo來展現一下,看了後,你一定會愛上它的,能讓你少寫很多JS語句。

1.View層

 

<span style="font-size:18px;">@*自動綁定實體模型*@@model MvcApplication1.Models.User<h2>Login</h2><form method="post">    @*綁定實體顯示名稱*@    @Html.LabelFor(user=>user.ID)    @*綁定實體值*@    @Html.TextBoxFor(user => user.ID)     @*驗證規則*@       @Html.ValidationMessageFor(user => user.ID)<br />    @Html.LabelFor(user=>user.Password)    @Html.EditorFor(user => user.Password)    @Html.ValidationMessageFor(user => user.Password)<br />    <input type="submit" name="提交" /></form>   </span>


2.Model層

 

<span style="font-size:18px;">using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.ComponentModel.DataAnnotations;using System.ComponentModel;namespace MvcApplication1.Models{    public class User    {        //必填項        [Required]        //介面綁定的名稱       [DisplayName("使用者別稱")]        //限制字元的長度        [StringLength(6,ErrorMessage="您輸入的名字太長了")]        //綁定的類型        [DataType(DataType.Text)]               //[Range(555555,999999)]        public string ID { get; set; }        [Required]        [DataType(DataType.Password)]        [DisplayName("使用者密碼")]        public string Password { get; set; }    }}</span>


3.Controller

 

<span style="font-size:18px;"> public ActionResult Login()        {            return View();        }        [HttpPost]        public ActionResult Login(User user)        {            if (user.ID =="Admin" || user.Password == "Admin")            {                return Content("登入成功");            }            else            {                return Content("密碼錯誤");            }                   }</span>

分析:整體實現的功能很簡單,就是把頁面傳進的值通過在Controller中驗證後返回結果,主要的功能就是在Model中引入了System.ComponentModel.DataAnnotations和System.ComponentModel的空間,然後為實體的屬性綁定了一些自定的驗證功能例如[Required]、 [DisplayName("使用者別稱")]、 [StringLength(6,ErrorMessage="您輸入的名字太長了")]等,當然這兩個命名空間中還有很多,有興趣的可以查一下。

 最終在介面上綁定強型別視圖的時候,通過反射機制,自動為每個控制項綁定實體屬性。





MVC中的驗證規則

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.