MVC4数据注释与验证
Using Validation Annotations
Required必须项验证属性
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
StringLength长度
[Required]
[StringLength()]
public string LastName { get; set; }
[Required]
[StringLength(, MinimumLength=)]
public string FirstName { get; set; }
RegularExpression正则表达式
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }
Range数字范围
[Range(,)]
public int Age { get; set; }
[Range(typeof(decimal), "0.00", "49.99")]
public decimal Price { get; set; }
Validation Attributes from System.Web.Mvc远程验证
[Remote("CheckUserName", "Account")]
public string UserName { get; set; }
public JsonResult CheckUserName(string username)
{
var result = Membership.FindUsersByName(username).Count == ;
return Json(result, JsonRequestBehavior.AllowGet);
}
匹配验证
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }
[Compare("Email")]
public string EmailConfirm { get; set; }
Custom Error Messages and Localization自定义错误消息和本地化
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",
ErrorMessage="Email doesn't look like a valid email address.")]
public string Email { get; set; }
[Required(ErrorMessage="Your last name is required")]
[StringLength(, ErrorMessage="Your last name is too long")]
public string LastName { get; set; }
[Required(ErrorMessage="Your {0} is required.")]
[StringLength(, ErrorMessage="{0} is too long.")]
public string LastName { get; set; }
[Required(ErrorMessageResourceType=typeof(ErrorMessages),
ErrorMessageResourceName="LastNameRequired")]
[StringLength(, ErrorMessageResourceType = typeof(ErrorMessages),
ErrorMessageResourceName = "LastNameTooLong")]
public string LastName { get; set; }
Looking behind the Annotation Curtain
Validation and Model Binding验证模型绑定
[HttpPost]
public ActionResult Create(Album album)
{
// the album parameter was created via model binding
// ..
}
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var album = storeDB.Albums.Find(id);
if(TryUpdateModel(album))
{
// ...
}
}
Validation and Model State验证模型状态
ModelState.IsValid == false
ModelState.IsValidField("LastName") == false
ModelState["LastName"].Errors.Count >
验证失败的信息
var lastNameErrorMessage = ModelState["LastName"].Errors[].ErrorMessage;
VIEW验证
@Html.ValidationMessageFor(m => m.LastName)
Controller Actions and Validation Errors控制器验证错误信息
[HttpPost]
public ActionResult AddressAndPayment(Order newOrder)
{
if (ModelState.IsValid)
{
newOrder.Username = User.Identity.Name;
newOrder.OrderDate = DateTime.Now;
storeDB.Orders.Add(newOrder);
storeDB.SaveChanges();
// Process the order
var cart = ShoppingCart.GetCart(this);
cart.CreateOrder(newOrder);
return RedirectToAction("Complete", new { id = newOrder.OrderId });
}
// Invalid -- redisplay with errors
return View(newOrder);
}
a啊
[HttpPost]
public ActionResult AddressAndPayment(FormCollection collection)
{
var newOrder = new Order();
TryUpdateModel(newOrder);
if (ModelState.IsValid)
{
newOrder.Username = User.Identity.Name;
newOrder.OrderDate = DateTime.Now;
storeDB.Orders.Add(newOrder);
storeDB.SaveChanges();
// Process the order
var cart = ShoppingCart.GetCart(this);
cart.CreateOrder(newOrder);
return RedirectToAction("Complete", new { id = newOrder.OrderId });
}
// Invalid -- redisplay with errors
return View(newOrder);
}
CUSTOM VALIDATION LOGIC自定义验证逻辑
继承ValidationAttribute
using System.ComponentModel.DataAnnotations;
namespace MvcMusicStore.Infrastructure
{
public class MaxWordsAttribute : ValidationAttribute
{
}
}
重写 IsValid
public class MaxWordsAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
return ValidationResult.Success;
}
}
完整自定义验证代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; namespace Mvc4.Infrastructure
{
public class MaxWordsAttribute : ValidationAttribute
{
public MaxWordsAttribute(int maxWords)
: base("{0} has too many words.")
{
_maxWords = maxWords;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
if (value != null)
{
var valueAsString = value.ToString();
if (valueAsString.Split(' ').Length > _maxWords)
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
private readonly int _maxWords;
} }
Model部分代码
[Required]
[StringLength()]
[MaxWords(, ErrorMessage="There are too many
words in {}")]
public string LastName { get; set; }
IValidatableObject模型中自定义验证类
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Mvc4.Infrastructure; namespace Mvc4.Models
{
public class Users : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (LastName != null &&
LastName.Split(' ').Length > )
{
yield return new ValidationResult("The last name has too many words!",
new[] { "LastName" });
}
}
[Required]
[StringLength()]
public string LastName { get; set; }
}
}
Display
[Required]
[StringLength(, MinimumLength=)]
[Display(Name="First Name")]
public string FirstName { get; set; }
自动生成编辑页面
<fieldset>
<legend>Shipping Information</legend>
@Html.EditorForModel()
</fieldset>
Order控制字段顺序
[Required]
[StringLength()]
[Display(Name="Last Name", Order=)]
[MaxWords(, ErrorMessage="There are too many words in {0}")]
public string LastName { get; set; }
[Required]
[StringLength(, MinimumLength=)]
[Display(Name="First Name", Order=)]
public string FirstName { get; set; }
隐藏属性Scaff oldColumn,使用EditorForModel生效
[ScaffoldColumn(false)]
public string Username { get; set; }
DisplayFormat格式化已短时间形式显示显示
[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString="{0:d}")]
public decimal Time{ get; set; }
ReadOnly只读属性,在页面上可以显示但无法将值传入控制器
[ReadOnly(true)]
public decimal Total { get; set; }
DataType数据类型
[Required]
[DataType(DataType.Password)]
[Display(Name="Password")]
public string Password { get; set; }
HiddenInput隐藏字段
MVC4数据注释与验证的更多相关文章
- MVC4数据注释与验证 2
Using Validation Annotations Required必须项验证属性 [Required] public string FirstName { get; set; } [Requi ...
- MVC4数据注解和验证
model中的验证注解特性: public class StuInfo { public int ID { get; set;} [Display(Name = "姓名")] // ...
- MVC4 数据验证、特性、自动属性总结
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精 最近在做自学MVC,遇到的问题很多,索性一点点总结 ...
- Code First 数据注释
Code First 数据注释 Julie Lerman http://thedatafarm.com 通过实体框架 Code First,可以使用您自己的域类表示 EF 执行查询.更改跟踪和更新函数 ...
- Yii 开发微信 '您提交的数据无法被验证'
使用Yii开发微信时,出现 [error][yii\web\HttpException:] exception 'yii\web\BadRequestHttpException' with messa ...
- MVC中的数据注解和验证
数据注解和验证 用户输入验证在客户端浏览器中需要执行验证逻辑. 在客户端也需要执行. 注解是一种通用机制, 可以用来向框架注入元数据, 同时, 框架不只驱动元数据的验证, 还可以在生成显示和编辑模型的 ...
- Entityframework Code First 系列之数据注释
上一篇<Entityframework Code First 系列之项目搭建>讲了搭建一个Code First的控制台项目.里面有一些内容并没有扩展出来讲,因为篇幅有限.这篇针对上面内容中 ...
- asp.net mvc常用的数据注解和验证以及entity framework数据映射
终于有时间整理一下asp.net mvc 和 entity framework 方面的素材了. 闲话少说,步入正题: 下面是model层的管理员信息表,也是大伙比较常用到的,看看下面的代码大伙应该不会 ...
- ASP.NET MVC4中的Model验证 移除指定验证信息
MVC中通过Model在页面间传值使的程序开发变得更加的快捷,但是很多时候,我们在数据传递的时候为了确保数据的有效性,要对Model的相关属性做基本的数据验证. 不多说直接上个代码,Model的实体类 ...
随机推荐
- 用js完成blog项目
//前台调用 var $ = function (args) { return new Base(args); } //基础库 function Base(args) { //创建一个数组,来保存获取 ...
- kali ssh 登录
kali 开启ssh 登录:可在windows 中通过 xshell 登录,方便操作. 修改sshd_config文件, vi /etc/ssh/sshd_config 将#PasswordAuthe ...
- Linker scripts之Intro
1 Intro Every link is controlled by a linker script. The main purpose of the linker script is to des ...
- 在fedora20下配置hadoop2.5.1的eclipse插件
(博客园-番茄酱原创) 在我的系统中,hadoop-2.5.1的安装路径是/opt/lib64/hadoop-2.5.1下面,然后hadoop-2.2.0的路径是/home/hadoop/下载/had ...
- T-SQL 变量
T-SQL变量 变量的种类: 在T-SQL中,变量按生存范围可以分为全局变量(Global Variable)和局部变量(Local Variable) 1.全局变量是由系统定义的,在整个SQL Se ...
- windows 无法启动asp.net 状态服务 错误 0x8007277a
处理方法:如果在启动ASP.NET State Service服务时遇到问题0x8007277a即无法启动或初始化,请尝试在命令行(CMD)中输入netsh winsock reset(有可能是wi ...
- C语言中返回字符串函数的四种实现方法 2015-05-17 15:00 23人阅读 评论(0) 收藏
C语言中返回字符串函数的四种实现方法 分类: UNIX/LINUX C/C++ 2010-12-29 02:54 11954人阅读 评论(1) 收藏 举报 语言func存储 有四种方式: 1.使用堆空 ...
- Codeforces 707 E. Garlands (二维树状数组)
题目链接:http://codeforces.com/problemset/problem/707/E 给你nxm的网格,有k条链,每条链上有len个节点,每个节点有一个值. 有q个操作,操作ask问 ...
- Mysql自增字段
1.关键字 auto_increment 2.自增用法 例: CREATE TABLE animals ( id mediumint not null auto_increment, name cha ...
- spring mvc学习(一)入门实例
springMVC处理流程如下: 通过配置DispacherServlet拦截指定的url,让后经HanddlerMapping来决定调用我自定义的Controller,在Controller中经过业 ...