日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

ASP.NET MVC中使用FluentValidation验证实体

發布時間:2024/9/20 asp.net 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET MVC中使用FluentValidation验证实体 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

  1、FluentValidation介紹

  FluentValidation是與ASP.NET DataAnnotataion Attribute驗證實體不同的數據驗證組件,提供了將實體與驗證分離開來的驗證方式,同時FluentValidation還提供了表達式鏈式語法。

  2、安裝FluentValidation

  FluentValidation地址:http://fluentvalidation.codeplex.com/

  使用Visual Studio的管理NuGet程序包安裝FluentValidation及FluentValidation.Mvc

  3、通過ModelState使用FluentValidation驗證

  項目解決方案結構圖:

  

  實體類Customer.cs:

using System; using System.Collections.Generic; using System.Linq; using System.Web;namespace Libing.Portal.Web.Models.Entities {public class Customer{public int CustomerID { get; set; }public string CustomerName { get; set; }public string Email { get; set; }public string Address { get; set; }public string Postcode { get; set; }public float? Discount { get; set; }public bool HasDiscount { get; set; }} }

  數據驗證類CustomerValidator.cs:

using System; using System.Collections.Generic; using System.Linq; using System.Web;using FluentValidation;using Libing.Portal.Web.Models.Entities;namespace Libing.Portal.Web.Models.Validators {public class CustomerValidator : AbstractValidator<Customer>{public CustomerValidator(){RuleFor(customer => customer.CustomerName).NotNull().WithMessage("客戶名稱不能為空");RuleFor(customer => customer.Email).NotEmpty().WithMessage("郵箱不能為空").EmailAddress().WithMessage("郵箱格式不正確");RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);RuleFor(customer => customer.Address).NotEmpty().WithMessage("地址不能為空").Length(20, 50).WithMessage("地址長度范圍為20-50字節");}} }

  控制器類CustomerController.cs:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc;using FluentValidation.Results;using Libing.Portal.Web.Models.Entities; using Libing.Portal.Web.Models.Validators;namespace Libing.Portal.Web.Controllers {public class CustomerController : Controller{public ActionResult Index(){return View();}public ActionResult Create(){return View();}[HttpPost]public ActionResult Create(Customer customer){CustomerValidator validator = new CustomerValidator();ValidationResult result = validator.Validate(customer);if (!result.IsValid){result.Errors.ToList().ForEach(error =>{ModelState.AddModelError(error.PropertyName, error.ErrorMessage);});}if (ModelState.IsValid){return RedirectToAction("Index");}return View(customer);}} }

  View頁面Create.cshtml,該頁面為在添加View時選擇Create模板自動生成:

@model Libing.Portal.Web.Models.Entities.Customer@{Layout = null; }<!DOCTYPE html><html> <head><meta name="viewport" content="width=device-width" /><title>Create</title> </head> <body>@using (Html.BeginForm()) {@Html.AntiForgeryToken()<div class="form-horizontal"><h4>Customer</h4><hr />@Html.ValidationSummary(true)<div class="form-group">@Html.LabelFor(model => model.CustomerName, new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.CustomerName)@Html.ValidationMessageFor(model => model.CustomerName)</div></div><div class="form-group">@Html.LabelFor(model => model.Email, new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Email)@Html.ValidationMessageFor(model => model.Email)</div></div><div class="form-group">@Html.LabelFor(model => model.Address, new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Address)@Html.ValidationMessageFor(model => model.Address)</div></div><div class="form-group">@Html.LabelFor(model => model.Postcode, new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Postcode)@Html.ValidationMessageFor(model => model.Postcode)</div></div><div class="form-group">@Html.LabelFor(model => model.Discount, new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Discount)@Html.ValidationMessageFor(model => model.Discount)</div></div><div class="form-group">@Html.LabelFor(model => model.HasDiscount, new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.HasDiscount)@Html.ValidationMessageFor(model => model.HasDiscount)</div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="Create" class="btn btn-default" /></div></div></div>} </body> </html>

  運行效果:

  

  4、通過設置實體類Attribute與驗證類進行驗證

  修改實體類Customer.cs:

using System; using System.Collections.Generic; using System.Linq; using System.Web;using FluentValidation.Attributes;using Libing.Portal.Web.Models.Validators;namespace Libing.Portal.Web.Models.Entities {[Validator(typeof(CustomerValidator))]public class Customer{public int CustomerID { get; set; }public string CustomerName { get; set; }public string Email { get; set; }public string Address { get; set; }public string Postcode { get; set; }public float? Discount { get; set; }public bool HasDiscount { get; set; }} }

  修改Global.asax.cs:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing;using FluentValidation.Attributes; using FluentValidation.Mvc;namespace Libing.Portal.Web {public class MvcApplication : System.Web.HttpApplication{protected void Application_Start(){AreaRegistration.RegisterAllAreas();RouteConfig.RegisterRoutes(RouteTable.Routes);// FluentValidation設置DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));}} }

  

總結

以上是生活随笔為你收集整理的ASP.NET MVC中使用FluentValidation验证实体的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。