转载: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' ...
随机推荐
- disruptor调优方法
翻译自disruptor在github上的文档,https://github.com/LMAX-Exchange/disruptor/wiki/Getting-Started Basic Tuning ...
- Day 1. 占位符的使用方法(%d,%s)(格式化输出)
方法1 name = input("请输入名字1") age = input ("请输入年龄") hobby = input("请输入兴趣爱好&qu ...
- 五,mysql优化——sql语句优化小技巧
1,大批量插入数据 (1)对于MyISAM: alter table table_name disable keys; loading data; alter table table_name ena ...
- Codeforces Round #452 (Div. 2) C. Dividing the numbers(水)
C. Dividing the numbers Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in t ...
- html基础+常用标签
概述 HTML是英文Hyper Text Mark-up Language(超文本标记语言)的缩写,他是一种制作万维网页面标准语言(标记).相当于定义统一的一套规则,大家都来遵守他,这样就可以让浏览器 ...
- Markdown 常用操作
1->水平线 注意,使用时发现,水平线的语句上一行必须为空行,不然水平线不生效 *** 或者 --- ------->效果: 2->标题 # 大 ## 大 ### 大 #### 大 ...
- bzoj 3027: [Ceoi2004]Sweet (生成函数)
题目传送门:https://www.lydsy.com/JudgeOnline/problem.php?id=3027. 题目大意:有$n$种数,每种有$C_i$个,问你在这些数中取出$[l,r]$个 ...
- 使用图片预加载,解决断网后无法从后台获取提示网络异常的logo图片的问题
项目中有需求,断网后,显示小提示窗,里面包含网络异常提示语和异常小logo图片. 在实际操作时,遇到,断网后,无法从后台获取异常小logo图片. 我是才用图片预加载的方法解决这个问题的,解决方法如下: ...
- webpack处理url资源的配置
webpack处理url资源的配置 1.安装 npm i url-loader -D 2.修改webpack.config.js const path = require('path'); // 启用 ...
- Android 开发工具类 28_sendGETRequest
以 GET 方式上传数据,小于 2K,且安全性要求不高的情况下. package com.wangjialin.internet.userInformation.service; import jav ...