ASP.NET MVC5驗證系列之Remote Validation
大多數(shù)的開發(fā)者,可能會遇到這樣的情況:當(dāng)我們在創(chuàng)建用戶之前,有必要去檢查是否數(shù)據(jù)庫中已經(jīng)存在相同名字的用戶。換句話說就是,我們要確保程序中,只有一個唯一的用戶名,不能有重復(fù)的。相信大多數(shù)人都有不同的解決方法,但是ASP.NET MVC中,為我們提供了一個特性,就是Remote Validation,用它可以解決類似這樣的問題。
Remote Validation調(diào)用了一個Ajax請求,可以是GET或者POST方式,接著調(diào)用方法,這個方法,至少要有一個參數(shù),并且方法的返回類型是Json格式的?!綧VC中通過JSOnResult來做到】,這個方法的參數(shù)就是要驗證的實體的屬性【必須,否則不能驗證,參數(shù)的大小寫無所謂?!浚绻@個驗證的方法返回值是true,那么就表名存在相同的用戶,我們就返回false,給前臺頁面。表明驗證不通過。
好了,直接說正題吧!
首先新建一個空白的MVC項目,在Model文件夾下,新建一個類RemoteUser:
public class RemoteUser
{
public string Name { get; set; }
public string Email { get; set; }
}
然后建一個測試的數(shù)據(jù)類:
public static class MyRemoteStaticData
{
public static List<RemoteUser> RemoteList
{
get
{
return new List<RemoteUser>()
{
new RemoteUser(){Name="Daniel",Email="Daniel@163.com"},
new RemoteUser(){Name="CFS",Email="CFS@163.com"}
};
}
}
}
在新建一個控制器MyRemoteController 【主要用來Remote驗證】:
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) //這里的參數(shù)名字,必須要和視圖中文本框控件的名字一樣,但大小寫無所謂
{
//如果存在用戶名,即isExists=true
bool isExists = MyRemoteStaticData.RemoteList.
Where(s => s.Name.ToLowerInvariant().
Equals(name.ToLower())).FirstOrDefault() != null;
//就向前臺返回false,表明已經(jīng)存在userName
return Json(!isExists,JsonRequestBehavior.AllowGet);
}
}
上面添加完驗證之后,我們來修改一下Model實體:
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 = "抱歉用戶名已經(jīng)存在!請重新輸入?。?!")]
public string Name { get; set; }
public string Email { get; set; }
}
}
然后在新建一個測試的控制器:
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插件。
@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>
然后修改一下默認(rèn)的路由:
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 }
);
}
運行項目:

輸入測試數(shù)據(jù):CFS,按Tab鍵后,自動就進行驗證了。

這里我們對Name字段就進行了Remote驗證,現(xiàn)在我想對Email字段進行驗證,需要使用到AdditionalFields,屬性,還需要另外添加一個驗證方法:
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) //這里的參數(shù)名字,必須要和視圖中文本框控件的名字一樣,但大小寫無所謂
{
//如果存在用戶名,即isExists=true
bool isExists = MyRemoteStaticData.RemoteList.
Where(s => s.Name.ToLowerInvariant().
Equals(name.ToLower())).FirstOrDefault() != null;
//就向前臺返回false,表明已經(jīng)存在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,表明已經(jīng)存在userName
return Json(!isExists, JsonRequestBehavior.AllowGet);
}
}
}
然后修改對應(yīng)的實體類:
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 = "抱歉用戶名已經(jīng)存在!請重新輸入?。?!")]
public string Name { get; set; }
//注意,這里的AdditionalFields="Name",Name字段必須和Modle中的字段完全一樣
[Remote("RemoteValidationAddtional", "MyRemote", AdditionalFields = "Name", ErrorMessage = "抱歉Email已經(jīng)存在!請重新輸入?。?!")]
public string Email { get; set; }
}
}
接著運行項目:
輸入在測試類中寫的測試數(shù)據(jù):

這里就對兩個字段進行了Remote Validation了。
上面使用了AdditionalFields 驗證字段,如果我們想要驗證不只一個字段,可以在AddtionalFiled里面添加,以逗號分隔就行了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ASP.NET中各種連接數(shù)據(jù)庫的配置的方法及json數(shù)據(jù)轉(zhuǎn)換
本篇文章主要介紹了ASP.NET中各種連接數(shù)據(jù)庫的配置的方法,詳細(xì)的介紹了MSSQL、Access、Oracle、SQLite、MySQL數(shù)據(jù)庫配置,具有一定的參考價值,有興趣的可以了解一下。2017-01-01
CorFlags.exe檢查.NET程序平臺目標(biāo)(Platform Target)的工具
.NET Framework SDK中的一個工具程序: CorFlags.exe。CorFlags.exe不但可查詢.NET組件的平臺目標(biāo)設(shè)定,甚至能直接修改設(shè)定,省去重新編譯的工夫。2013-02-02
asp.net(c#)限制用戶輸入規(guī)定的字符和數(shù)字的代碼
這幾天在看到一個網(wǎng)站的注冊的時候,就只允許輸入規(guī)定的字符和數(shù)字。我就好奇的寫了一個校驗的代碼。呵呵 不知道對大家有沒有用。如果有用的話可以保存。沒有用就當(dāng)是看看以下了。2010-10-10
Excel、記事本數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫的實現(xiàn)方法
將手機號批量導(dǎo)入數(shù)據(jù)庫。思路:先將要導(dǎo)入的文件傳上項目里,然后讀取文件的每行數(shù)據(jù)并插入數(shù)據(jù)庫,操作完后再將上傳的文件刪除2013-10-10
如何在ASP.NET Core應(yīng)用程序運行Vue并且部署在IIS上詳解
這篇文章主要給大家介紹了關(guān)于如何運行Vue在ASP.NET Core應(yīng)用程序并且部署在IIS上的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-10-10
Asp.net MVC中Razor常見的問題與解決方法總結(jié)
這篇文章主要給大家介紹了關(guān)于Asp.net MVC中Razor常見的問題與解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面跟著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-08-08

