期货大赛项目|四,MVC的数据验证
上图先看下效果
样式先不说,先了解下数据验证是怎么实现的
一 必须是强类型的视图
二 这些显示提示的话语,都在强类型的实体中
三 必须使用Html.BeginForm或者Html.AjaxBeginForm
四 提交方式必须是form的submit
上代码
@model FuturesContest.ViewModel.User.UserViewModel
@{
Layout = null;
} <!DOCTYPE html> <html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- Meta, title, CSS, favicons, etc. -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>期货大赛管理后台登录! | </title>
<!-- Bootstrap -->
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<!-- Font Awesome -->
<link href="~/Content/vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
<!-- NProgress -->
<link href="~/Content/vendors/nprogress/nprogress.css" rel="stylesheet">
<!-- Animate.css -->
<link href="~/Content/vendors/animate.css/animate.min.css" rel="stylesheet">
<!--poshytip.css-->
<link href="~/Content/vendors/poshytip-1.2/src/tip-yellow/tip-yellow.css" rel="stylesheet" />
<!-- Custom Theme Style -->
<link href="~/Content/Gentelella/custom.min.css" rel="stylesheet" />
</head>
<body class="login">
<div>
<a class="hiddenanchor" id="signup"></a>
<a class="hiddenanchor" id="signin"></a>
<div class="login_wrapper">
<div class="animate login_form">
<section class="login_content">
@{
Html.EnableClientValidation();
}
@using (Html.BeginForm("Index", "Login", FormMethod.Post))
{
<h1>期货大赛管理后台</h1>
<div>
@Html.TextBoxFor(m => m.Account, new {@class = "form-control", placeholder = "用户名", autocomplete="off"})
@Html.ValidationMessageFor(m => m.Account)
</div>
<div>
@Html.PasswordFor(m => m.Password, new {@class = "form-control", placeholder = "密码", autocomplete = "off" })
@Html.ValidationMessageFor(m => m.Password)
</div>
<div>
<a id="sub_login" class="btn btn-default submit">登 录</a>
</div>
<div class="clearfix"></div>
}
</section>
</div>
</div>
</div>
</body>
</html>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Content/vendors/poshytip-1.2/src/jquery.poshytip.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/common.js"></script>
<script type="text/javascript">
$("#sub_login").click(function() {
$("form").submit();
}); document.onkeydown = function() {
if (event.keyCode === 13) {
$("form").submit();
}
}
</script>
@{
Html.EnableClientValidation();
}
启动客户端验证
@using (Html.BeginForm("Index", "Login", FormMethod.Post))
benginForm提交
@Html.TextBoxFor(m => m.Account, new {@class = "form-control", placeholder = "用户名", autocomplete="off"})
@Html.ValidationMessageFor(m => m.Account)
ValidationMessageFor错误信息会显示在这里
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Content/vendors/poshytip-1.2/src/jquery.poshytip.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/common.js"></script>
千万不要忘记unobtrusive.js
后台
[HttpPost]
public ActionResult Index(UserViewModel user)
{
var model = user.ToEntity(); if (!_bll.IsRightPassword(model))
ModelState.AddModelError("Password", "密码错误或该用户被禁用");
if (!ModelState.IsValid)
return View(user); //登录成功,将登录信息存入session
var loginInfo = _bll.GetUserByAccount(model.Account);
Session["LoginInfo"] = loginInfo;
//将登录信息存储到cookies
_bll.SaveCookie(loginInfo); return RedirectToAction("Index", "Back");
}
ModelState.AddModelError 可以添加一个错误信息
ModelState.IsValid 表示所有数据通过验证
在看看viewModel验证的几种类型
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc; namespace FuturesContest.ViewModel.User
{
public class UserAddViewModel
{
public int Id { get; set; } [DisplayName("用户名")]
[Required(ErrorMessage = "{0}不能为空")]
[Remote("CheckAccount", "Back", ErrorMessage = "{0}已存在")]
public string Account { get; set; } [DisplayName("密码")]
[Required(ErrorMessage = "{0}不能为空")]
[RegularExpression(@"^[0-9A-Za-z]{6,20}$",ErrorMessage = "{0}格式为6-20位字母或数字")]
public string Password { get; set; } [DisplayName("昵称")]
[Required(ErrorMessage = "{0}不能为空")]
[Remote("CheckNickName", "Back", ErrorMessage = "{0}已存在")]
public string NickName { get; set; } [DisplayName("有效状态")]
public int IsEnabled { get; set; } [DisplayName("创建时间")]
public DateTime AddTime { get; set; } [DisplayName("最后登录时间")]
public DateTime LastTime { get; set; } [DisplayName("头像")]
public string HeadThumb { get; set; } [DisplayName("排序")]
[Required(ErrorMessage = "{0}不能为空")]
[Range(, , ErrorMessage="{0}取值范围为0-99")]
public int OrderId { get; set; }
}
}
DisplayName-------------- 在用labelFor的时候,会显示后面的名称
[Required(ErrorMessage = "{0}不能为空")] ------------非空验证
[Remote("CheckAccount", "Back", ErrorMessage = "{0}已存在")] ---------Ajax验证,需要后台有一个CheckAccount的方法
[RegularExpression(@"^[0-9A-Za-z]{6,20}$",ErrorMessage = "{0}格式为6-20位字母或数字")]----------正则验证
[Range(0, 99, ErrorMessage="{0}取值范围为0-99")]------------范围验证
ajax验证的案例
//Ajax验证用户名是否存在
public JsonResult CheckAccount(string account)
{
var result = _bll.ExistAccount(account);
return Json(result, JsonRequestBehavior.AllowGet);
}
返回的一定是一个布尔值,才能知道是否通过
好啦!现在应该已经可以正常的显示数据验证的错误信息了!但样式不好看,所以我们要修改样式
我用的是poshytip插件,类似于tips的插件
引入对应的css和js
修改源码
找到jquery.validate.unobtrusive.js
找到function onError(error, inputElement)函数,稍微改改就可以 我贴个全的
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
//------为container添加tips样式 start--------
var $customErrorTip = container.attr("data-forerrortip");
//------为container添加tips样式 end----------
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
//-----添加提示消息 start -------
var elem = $("#" + inputElement[0].name.replace(".", "_"));
//-----添加提示消息 end ---------
if (replace) {
container.empty();
//add start
if (error.html() != "") {
if ($customErrorTip) {
$("#" + $customErrorTip).poshytip("destroy");
} else {
elem.poshytip("destroy");
}
var direction = "right";
//左边+元素宽+提示的文字+提示两边的空白
if ((elem[0].offsetLeft + elem.width() + error.length * 10 + 20) > $(document).width()) {
direction = "left";
}
var errorConfig = {
content: error,
alignTo: 'target',
alignX: direction,
alignY: 'center',
showOn: 'none',
bgImageFrameSize: 7,
offsetX: 5
};
if ($customErrorTip) {
$("#" + $customErrorTip).poshytip(errorConfig).poshytip('show');
} else {
elem.filter(':not(.valid)').poshytip(errorConfig).poshytip('show');
}
} else {
if ($customErrorTip) {
$("#" + $customErrorTip).poshytip("destroy");
} else {
elem.poshytip("destroy");
}
}
//add end
//error.removeClass("input-validation-error").appendTo(container);
}
else {
error.hide();
}
}
这样我们就解决了通过微软的这个js进行前端验证的样式修改
注意:这种验证没有到服务器验证,只是JS拦截
但!!!!还是不够,Ajax方法的后台验证样式并不通过这个js,它是后端验证,直接返回到前端的
所以我封装了一个js,捕获返回的数据进行修改
common,js
$(function () {
$(".field-validation-error").each(function () {
var $this = $(this);
var thisid = $this.attr("data-valmsg-for").replace(".", "_");
var direction = "right";
// 左边+元素宽+提示的文字+提示两边的空白
if (($this[0].offsetLeft + $this.width() + $this.text().length * 10 + 20) > $(document).width()) {
direction = "left";
}
$this.hide(); setTimeout(function () {
$("#" + thisid).poshytip({
content: $this.text(),
alignTo: 'target',
alignX: direction,
alignY: 'center',
showOn: 'none',
offsetX: 5
}).poshytip('show');
}, 100); });
});
到这时,我们才完成了MVC的数据验证!!!
期货大赛项目|四,MVC的数据验证的更多相关文章
- 期货大赛项目|十,MVC对js和css的压缩
在Global.asax中添加两行代码 //默认在调试期间,不会启用js和css的压缩 //下面的语句确保了在调试期间也压缩css和js BundleTable.EnableOptimizations ...
- MVC中数据验证
http://www.studyofnet.com/news/339.html http://www.cnblogs.com/kissdodog/archive/2013/05/04/3060278. ...
- <转>ASP.NET学习笔记之MVC 3 数据验证 Model Validation 详解
MVC 3 数据验证 Model Validation 详解 再附加一些比较好的验证详解:(以下均为引用) 1.asp.net mvc3 的数据验证(一) - zhangkai2237 - 博客园 ...
- MVC 多种 数据验证 post
技术:c# .net 采用mvc框架,实现model的数据验证. 刚开始觉得数据验证很方便,可以判断非空.数据正确性,但是后来发现很多需要数据库的判定还是需要post请求做,但是就想mvc的数据验证 ...
- MVC Model数据验证
概述 上节我们学习了Model的数据在界面之间的传递,但是很多时候,我们在数据传递的时候为了确保数据的有效性,不得不给Model的相关属性做基本的数据验证. 本节我们就学习如何使用 System.Co ...
- ASP.NET MVC 扩展数据验证 转
此文只作记录 public class MaxWordsAttribute : ValidationAttribute { public MaxWordsAttribute(int maxWords) ...
- MVC 3 数据验证 Model Validation 详解
在MVC 3中 数据验证,已经应用的非常普遍,我们在web form时代需要在View端通过js来验证每个需要验证的控件值,并且这种验证的可用性很低.但是来到了MVC 新时代,我们可以通过MVC提供的 ...
- [转]MVC自定义数据验证(两个时间的比较)
本文转自:http://www.cnblogs.com/zhangliangzlee/archive/2012/07/26/2610071.html Model: public class Model ...
- (转)MVC 3 数据验证 Model Validation 详解
继续我们前面所说的知识点进行下一个知识点的分析,这一次我们来说明一下数据验证.其实这是个很容易理解并掌握的地方,但是这会浪费大家狠多的时间,所以我来总结整理一下,节约一下大家宝贵的时间. 在MVC 3 ...
随机推荐
- Windows PowerShell 入門(9)-エラー編
対象読者 Windows PowerShellでコマンドレット操作ができる方 何らかのプログラミング経験があればなお良い 必要環境 Windows PowerShell エラーをリダイレクトする リダ ...
- RDLC系列之一 简介和入门
一.简介 RDLC报表,通过Report Viewer Control来实现,制作微软RDLC报表由以下三部分构成:1.制作自己的DateSet集合(就是报表的数据集):2.制作自己的报表文件.rdl ...
- LSH(Locality Sensitive Hashing)原理与实现
原文地址:https://blog.csdn.net/guoziqing506/article/details/53019049 LSH(Locality Sensitive Hashing)翻译成中 ...
- POJ3580 SuperMemo splay伸展树,区间操作
题意:实现一种数据结构,支持对一个数列的 6 种操作:第 x 个数到第 y 个数之间的数每个加 D:第 x 个数到第 y 个数之间全部数翻转:第 x 个数到第 y 个数之间的数,向后循环流动 c 次, ...
- List<> of struct with property. Cannot change value of property. why?
这个返回如下错误:"Cannot modify the return value of 'System.Collections.Generic.List<MyStruct>.th ...
- (常用)xml-pickle-shevel-json模块
json,pickle模块 1. 什么是序列化 序列化指的是将内存中的数据类型转换成一种中间格式,该格式可以用来存到硬盘中或者基于网络传输 2. 为 ...
- 模块 -- 序列化 hashlib sha logging (加密 加盐 )
模块: 一个py文件就是一个模块 模块分类: 1:内置模块,登录模块,时间模块,sys模块,os模块等等 2: 扩展模块, 3:自定义模块,自己写的py文件 python 开发效率之高:python ...
- 搭建python的虚拟环境
文章连接:https://www.cnblogs.com/zlsgh/p/8485848.html ubuntu系统下Python虚拟环境的安装和使用 前言:进行python项目开发的时 ...
- Tp5自动验证
<?php class DB { private $address = 'mysql.21future.com'; private $username = 'manbang'; private ...
- Linux文件系统深度讨论【转】
本文旨在对Linux文件系统概念高级工作方式进行的讨论,不是对特定文件系统类型(如EXT4)如何工作的低级描述,也不是对文件系统命令的教程. 每台通用计算机都需要将各种类型的数据存储在硬盘驱动器( ...