ASP.NET MVC5驗(yàn)證系列之服務(wù)端驗(yàn)證
這篇文章,我將會說到,使用數(shù)據(jù)注解API來進(jìn)行服務(wù)端驗(yàn)證。ASP.NET MVC 框架在執(zhí)行的時候,驗(yàn)證所有傳遞到控制器的數(shù)據(jù),如果驗(yàn)證失敗就把錯誤消息,填充到ModelState對象中,并且把這個對象傳遞給控制器,然后控制器中的方法,根據(jù)Modelstate的狀態(tài)來判斷,是否驗(yàn)證失敗還是驗(yàn)證通過。
在這里,我將會使用兩種方法來驗(yàn)證數(shù)據(jù)的合法性,一個是手動添加錯誤消息到ModelState對象中,另外一個方法是使用數(shù)據(jù)注解【Data Annotation】 API,來做。
先來看看使用手動驗(yàn)證的方式吧:
我們新建一個空白的MVC項目:添加一個Student實(shí)體:
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)
{
//服務(wù)端驗(yàn)證,方法一,手動添加錯誤消息到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");
}
}
//實(shí)體驗(yàn)證通過
if (ModelState.IsValid)
{
ViewBag.Name = model.Name;
ViewBag.Email = model.Email;
}
return View(model);
}
}
}
創(chuàng)建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的狀態(tài)
if (ViewData.ModelState.IsValid)
{
if (ViewBag.Name != null)
{
<b>
Name:@ViewBag.Name<br/>
Email:@ViewBag.Email
</b>
}
}
<fieldset>
<legend>Student</legend>
<div>
@*生成label標(biāo)簽*@
@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>
然后,修改一下默認(rèn)的路由:
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 }
);
}
運(yùn)行之后,報錯。查找了一下原因,修改了一下視圖代碼:

運(yùn)行之后,

接著驗(yàn)證一下,Name不為空,Email輸入非法格式的數(shù)據(jù):

最后驗(yàn)證一下,輸入合法的數(shù)據(jù):

好了,現(xiàn)在看看第二種方式,使用數(shù)據(jù)注解來進(jìn)行服務(wù)端驗(yàn)證:
新建一個類:避免混淆,
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();
}
對應(yīng)的視圖:
@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>

首先驗(yàn)證,都為空的情況:

Name不為空,Email為空

Name不為空,Email輸入非法格式數(shù)據(jù)

兩個都輸入合法的數(shù)據(jù):

好了,以上就是MVC中服務(wù)端驗(yàn)證了,我們一般是使用第二種,來進(jìn)行驗(yàn)證。也就是數(shù)據(jù)注解。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ASP.NET?MVC使用jQuery?ui的progressbar實(shí)現(xiàn)進(jìn)度條
這篇文章介紹了ASP.NET?MVC使用jQuery?ui的progressbar實(shí)現(xiàn)進(jìn)度條的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08
ASP.NET網(wǎng)站使用Kindeditor富文本編輯器配置步驟
首先下載編輯器然后部署編輯器最后在網(wǎng)頁中加入(ValidateRequest="false")引入腳本文件,具體配置步驟如下,有需求的朋友可以了解下哈2013-06-06
MVC、MVP和MVVM分別是什么_動力節(jié)點(diǎn)Java學(xué)院整理
MVC,MVP 和 MVVM分別是什么?MVC(Model-View-Controller)是最常見的軟件架構(gòu)之一,業(yè)界有著廣泛應(yīng)用。它本身很容易理解,但是要講清楚,它與衍生的 MVP 和 MVVM 架構(gòu)的區(qū)別就不容易了。2017-08-08
ASP.NET生成eurl.axd Http異常錯誤的處理方法
在IIS6中同時啟用了ASP.NET 2.0 和 ASP.NET 4.0 后,網(wǎng)站程序可能會出現(xiàn)如下錯誤:“ System.Web.HttpException: Path ‘//eurl.axd/‘ was not found. ”2011-05-05

