大多數的開發者,可能會遇到這樣的情況:當我們在創建用戶之前,有必要去檢查是否數據庫中已經存在相同名字的用戶。換句話說就是,我們要確保程序中,只有一個唯一的用戶名,不能有重復的。相信大多數人都有不同的解決方法,但是ASP.NET MVC中,為我們提供了一個特性,就是Remote Validation,用它可以解決類似這樣的問題。
Remote Validation調用了一個Ajax請求,可以是GET或者POST方式,接著調用方法,這個方法,至少要有一個參數,并且方法的返回類型是Json格式的。【MVC中通過JSOnResult來做到】,這個方法的參數就是要驗證的實體的屬性【必須,否則不能驗證,參數的大小寫無所謂。】,如果這個驗證的方法返回值是true,那么就表名存在相同的用戶,我們就返回false,給前臺頁面。表明驗證不通過。
好了,直接說正題吧!
首先新建一個空白的MVC項目,在Model文件夾下,新建一個類RemoteUser:
1
2
3
4
5
6
|
public class RemoteUser { public string Name { get ; set ; } public string Email { get ; set ; } } |
然后建一個測試的數據類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public static class MyRemoteStaticData { public static List<RemoteUser> RemoteList { get { return new List<RemoteUser>() { }; } } } |
在新建一個控制器MyRemoteController 【主要用來Remote驗證】:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
using Server_Side_Validation_IN_MVC.StaticData; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Server_Side_Validation_IN_MVC.Controllers { public class MyRemoteController : Controller { // GET: MyRemote public JsonResult RemoteValidate( string name) //這里的參數名字,必須要和視圖中文本框控件的名字一樣,但大小寫無所謂 { //如果存在用戶名,即isExists=true bool isExists = MyRemoteStaticData.RemoteList. Where(s => s.Name.ToLowerInvariant(). Equals(name.ToLower())).FirstOrDefault() != null ; //就向前臺返回false,表明已經存在userName return Json(!isExists,JsonRequestBehavior.AllowGet); } } |
上面添加完驗證之后,我們來修改一下Model實體:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Server_Side_Validation_IN_MVC.Models { public class RemoteUser { [Remote( "RemoteValidate" , "MyRemote" , ErrorMessage = "抱歉用戶名已經存在!請重新輸入!!!" )] public string Name { get ; set ; } public string Email { get ; set ; } } } |
然后在新建一個測試的控制器:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Server_Side_Validation_IN_MVC.Controllers { public class UserController : Controller { public ActionResult AddRemoteUser() { return View(); } } } |
添加AddRemoteUser視圖,【注意這里,Remote Validation是需要引入Jquery插件和啟用客戶端驗證的】
這里勾選引入腳本庫,也主要是用來引入Jquery插件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
@model Server_Side_Validation_IN_MVC.Models.RemoteUser @{ ViewBag.Title = "AddRemoteUser"; } < h2 >AddRemoteUser</ h2 > @using (Html.BeginForm()) { @Html.AntiForgeryToken() < div class = "form-horizontal" > < h4 >RemoteUser</ h4 > < hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) < div class = "form-group" > @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) < div class = "col-md-10" > @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" }) </ div > </ div > < div class = "form-group" > @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" }) < div class = "col-md-10" > @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" }) </ 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 > } < div > @Html.ActionLink("Back to List", "Index") </ div > < script src = "~/Scripts/jquery-1.10.2.min.js" ></ script > < script src = "~/Scripts/jquery.validate.min.js" ></ script > < script src = "~/Scripts/jquery.validate.unobtrusive.min.js" ></ script > |
然后修改一下默認的路由:
1
2
3
4
5
6
7
8
9
10
|
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" ); routes.MapRoute( name: "Default" , url: "{controller}/{action}/{id}" , defaults: new { controller = "User" , action = "AddRemoteUser" , id = UrlParameter.Optional } ); } |
運行項目:
輸入測試數據:CFS,按Tab鍵后,自動就進行驗證了。
這里我們對Name字段就進行了Remote驗證,現在我想對Email字段進行驗證,需要使用到AdditionalFields,屬性,還需要另外添加一個驗證方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
using Server_Side_Validation_IN_MVC.StaticData; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Server_Side_Validation_IN_MVC.Controllers { public class MyRemoteController : Controller { // GET: MyRemote public JsonResult RemoteValidate( string name) //這里的參數名字,必須要和視圖中文本框控件的名字一樣,但大小寫無所謂 { //如果存在用戶名,即isExists=true bool isExists = MyRemoteStaticData.RemoteList. Where(s => s.Name.ToLowerInvariant(). Equals(name.ToLower())).FirstOrDefault() != null ; //就向前臺返回false,表明已經存在userName return Json(!isExists,JsonRequestBehavior.AllowGet); } public JsonResult RemoteValidationAddtional( string name, string email) { //如果存在用戶名,即isExists=true bool isExists = MyRemoteStaticData.RemoteList. Where(s => s.Name.ToLowerInvariant(). Equals(name.ToLower()) && s.Email.ToLowerInvariant().Equals(email.ToLower())).FirstOrDefault() != null ; //就向前臺返回false,表明已經存在userName return Json(!isExists, JsonRequestBehavior.AllowGet); } } } |
然后修改對應的實體類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Server_Side_Validation_IN_MVC.Models { public class RemoteUser { [Remote( "RemoteValidate" , "MyRemote" , ErrorMessage = "抱歉用戶名已經存在!請重新輸入!!!" )] public string Name { get ; set ; } //注意,這里的AdditionalFields="Name",Name字段必須和Modle中的字段完全一樣 [Remote( "RemoteValidationAddtional" , "MyRemote" , AdditionalFields = "Name" , ErrorMessage = "抱歉Email已經存在!請重新輸入!!!" )] public string Email { get ; set ; } } } |
接著運行項目:
輸入在測試類中寫的測試數據:
這里就對兩個字段進行了Remote Validation了。
上面使用了AdditionalFields 驗證字段,如果我們想要驗證不只一個字段,可以在AddtionalFiled里面添加,以逗號分隔就行了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。