這篇文章,我將會說到,使用資料註解API來進行服務端驗證。ASP.NET MVC 架構在執行的時候,驗證所有傳遞到控制器的資料,如果驗證失敗就把錯誤訊息,填充到ModelState對象中,並且把這個對象傳遞給控制器,然後控制器中的方法,根據Modelstate的狀態來判斷,是否驗證失敗還是驗證通過。
在這裡,我將會使用兩種方法來驗證資料的合法性,一個是手動添加錯誤訊息到ModelState對象中,另外一個方法是使用資料註解【Data Annotation】 API,來做。
先來看看使用手動驗證的方式吧:
我們建立一個空白的MVC項目:添加一個Student實體:
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Server_Side_Validation_IN_MVC.Models{ public class Student { public string Name { get; set; } public string Email { get; set; } }}
然後添加一個Student控制器:
using Server_Side_Validation_IN_MVC.Models;using System;using System.Collections.Generic;using System.Linq;using System.Text.RegularExpressions;using System.Web;using System.Web.Mvc;namespace Server_Side_Validation_IN_MVC.Controllers{ public class StudentController : Controller { // GET: Student public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(Student model) { //服務端驗證,方法一,手動添加錯誤訊息到ModelState對象中 //如果Name是空的 if (string.IsNullOrEmpty(model.Name)) { ModelState.AddModelError("Name", "Name is required"); } //如果Email是空的 if (string.IsNullOrEmpty(model.Email)) { ModelState.AddModelError("Email", "Email is required"); } else { string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" + @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; Regex re = new Regex(emailRegex); //Email不為空白的時候,但格式不合法 if (!re.IsMatch(model.Email)) { ModelState.AddModelError("Email", "Email is not valid"); } } //實體驗證通過 if (ModelState.IsValid) { ViewBag.Name = model.Name; ViewBag.Email = model.Email; } return View(model); } }}
建立Index視圖:
@model Server_Side_Validation_IN_MVC.Models.Student@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>Index</title></head><body> <div> @using (Html.BeginForm()) { //使用ViewData.ModelState.IsValid來判斷ModelState的狀態 if (ViewData.ModelState.IsValid) { if (ViewBag.Name != null) { <b> Name:@ViewBag.Name<br/> Email:@ViewBag.Email </b> } } <fieldset> <legend>Student</legend> <div> @*產生label標籤*@ @Html.LabelFor(model=>model.Name) </div> <div> @*產生文字框*@ @Html.EditorFor(model=>model.Name) @*不合法*@ //// @if (!ViewData.ModelState.IsValid)//這樣寫有問題正確的寫法: @if (!ViewData.ModelState.IsValid &&ViewData.ModelState["Email"].Errors.Count>0) { //從字典中擷取錯誤訊息:@ViewData.ModelState["Name"].Errors[0].ErrorMessage <span style="color:red">@ViewData.ModelState["Name"].Errors[0].ErrorMessage</span> } </div> <div> @Html.LabelFor(model=>model.Email) </div> <div> @Html.EditorFor(model=>model.Email) /////@if (!ViewData.ModelState.IsValid) 這樣寫有問題: // 正確的寫法在下面 @if (!ViewData.ModelState.IsValid &&ViewData.ModelState["Email"].Errors.Count>0) { //從字典中擷取錯誤訊息:@ViewData.ModelState["Email"].Errors[0].ErrorMessage <span style="color:red">@ViewData.ModelState["Email"].Errors[0].ErrorMessage</span> } </div> <p> <input type="submit" value="Create"/> </p> </fieldset> } </div></body></html>
然後,修改一下預設的路由:
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional } ); }
運行之後,報錯。尋找了一下原因,修改了一下視圖代碼:
運行之後,
接著驗證一下,Name不為空白,Email輸入非法格式的資料:
最後驗證一下,輸入合法的資料:
好了,現在看看第二種方式,使用資料註解來進行服務端驗證:
建立一個類:避免混淆,
using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Web;namespace Server_Side_Validation_IN_MVC.Models{ public class StudentServer { [Required(ErrorMessage="Name為必填項")] public string Name { get; set; } [Required(ErrorMessage="電子郵件必須")] [EmailAddress(ErrorMessage="電子郵件格式不對")] public string Email { get; set; } }}
在控制器中建立兩個方法:
public ActionResult SeverSideIndex() { return View(); } [HttpPost] public ActionResult SeverSideIndex(StudentServer model) { if (ModelState.IsValid) { ViewBag.Name = model.Name; ViewBag.Email = model.Email; } return View(); }
對應的視圖:
@model Server_Side_Validation_IN_MVC.Models.StudentServer@{ Layout = null;}@if (ViewData.ModelState.IsValid){ if (ViewBag.Name != null) { <b> Name:@ViewBag.Name<br /> Email:@ViewBag.Email </b> }}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>SeverSideIndex</title></head><body> <div> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Student</legend> <div> @Html.LabelFor(model=>model.Name) </div> <div> @Html.EditorFor(model=>model.Name) @Html.ValidationMessageFor(model=>model.Name) </div> <div> @Html.LabelFor(model => model.Email) </div> <div> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <p> <input type="submit" value="Create"/> </p> </fieldset> } </div></body></html>
首先驗證,都為空白的情況:
Name不為空白,Email為空白
Name不為空白,Email輸入非法格式資料
兩個都輸入合法的資料:
好了,以上就是MVC中服務端驗證了,我們一般是使用第二種,來進行驗證。也就是資料註解。
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。