转载:Remote Validation
http://www.jb51.net/article/89474.htm
大多数的开发者,可能会遇到这样的情况:当我们在创建用户之前,有必要去检查是否数据库中已经存在相同名字的用户。换句话说就是,我们要确保程序中,只有一个唯一的用户名,不能有重复的。相信大多数人都有不同的解决方法,但是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>() { new RemoteUser(){Name= "Daniel" ,Email= "Daniel@163.com" }, new RemoteUser(){Name= "CFS" ,Email= "CFS@163.com" } }; } } } |
在新建一个控制器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里面添加,以逗号分隔就行了。
转载:Remote Validation的更多相关文章
- MVC学习系列13--验证系列之Remote Validation
大多数的开发者,可能会遇到这样的情况:当我们在创建用户之前,有必要去检查是否数据库中已经存在相同名字的用户.换句话说就是,我们要确保程序中,只有一个唯一的用户名,不能有重复的.相信大多数人都有不同的解 ...
- Implementing Remote Validation in MVC
Using Validation Code Step 1: Create model for Catalog table and apply the the remote validation for ...
- asp net core Remote Validation 无法验证
[注意这里,Remote Validation是需要引入Jquery插件和启用客户端验证的]
- 转载 jQuery validation
之前做客户端验证感觉自己javascript 不行,虽然能写出来一完整的验证,但从不自信,一直觉得客户端验证是比较繁琐的事情,但是又不能不做,只到最开始接触ajax ,遇到了一个jQuery vali ...
- [转载]Remote Desktop Manager 9.0.10.0 Enterprise 附企业版注册码 (强大的远程控制软件)
http://www.52xiazai.net/pcsoft/network/yuanchen/20131206/2429.html
- Model Validation in Asp.net MVC
原文:Model Validation in Asp.net MVC 本文用于记录Pro ASP.NET MVC 3 Framework中阐述的数据验证的方式. 先说服务器端的吧.最简单的一种方式自然 ...
- MVC学习系列4--@helper辅助方法和用户自定义HTML方法
在HTML Helper,帮助类的帮助下,我们可以动态的创建HTML控件.HTML帮助类是在视图中,用来呈现HTML内容的.HTML帮助类是一个方法,它返回的是string类型的值. HTML帮助类, ...
- Chapter 2: Design the user experience
Apply the user interface design for a web application 介绍了Css的常用属性和html5的新element,以及Htmlhelper的简单方法,如 ...
- Extjs 表单验证后,几种错误信息展示方式
今天要求对form表单验证,进行系统学习一下,故做了几个示例: Ext.onReady(function(){ var panel=Ext.create('Ext.form.Panel' ...
随机推荐
- Android------------fragment数据传递
一.activity向fragment的数值之间的传递 关键点:fragment.setArguments(bundle);---->activity发出的信息 Bundle bund ...
- 740. Delete and Earn
Given an array nums of integers, you can perform operations on the array. In each operation, you pic ...
- Django + DRF + Elasticsearch 实现搜索功能
django使用haystack来调用Elasticsearch搜索引擎 如何使用django来调用Elasticsearch实现全文的搜索 Haystack为Django提供了模块化的搜索.它的特 ...
- webpack快速入门——配置文件:入口和出口,多入口、多出口配置
1.在根目录新建一个webpack.config.js文件,然后开始配置: const path = require('path'); module.exports={ //入口文件的配置项 entr ...
- 用switch函数根据选择不同的radio出现不同的视图
html代码: <!DOCTYPE html> <html> <head> <title></title> <style type=& ...
- 数据结构---平衡查找树之B树和B+树(转)
本文转载自:http://www.cnblogs.com/yangecnu/p/Introduce-B-Tree-and-B-Plus-Tree.html 前面讲解了平衡查找树中的2-3树以及其实现红 ...
- POJ 1147
#include <iostream> #include <algorithm> #define MAXN 3005 using namespace std; int _m[M ...
- rabbitmq系列三 之发布/订阅
1.发布/订阅 在上篇教程中,我们搭建了一个工作队列,每个任务只分发给一个工作者(worker).在本篇教程中,我们要做的跟之前完全不一样 —— 分发一个消息给多个消费者(consumers).这种模 ...
- C#获取获取北京时间多种方法
#region 获取网络时间 ///<summary> /// 获取中国国家授时中心网络服务器时间发布的当前时间 ///</summary> ///<returns> ...
- if嵌套语句 shell脚本实例 测试是否闰年
在 if 语句里面,你可以使用另外一个 if 语句.只要你能逻辑管理 你就可以使用多层嵌套. 以下是一个测试闰年的例子: #!/bin/bash # This script will test if ...