MVC4数据注释与验证

Using Validation Annotations

Required必须项验证属性

[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }

StringLength长度

[Required]
[StringLength(160)]
public string LastName { get; set; }
[Required]
[StringLength(160, MinimumLength=3)]
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(35,44)]
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 == 0;
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(160, ErrorMessage="Your last name is too long")]
public string LastName { get; set; }
[Required(ErrorMessage="Your {0} is required.")]
[StringLength(160, ErrorMessage="{0} is too long.")]
public string LastName { get; set; }
[Required(ErrorMessageResourceType=typeof(ErrorMessages),
ErrorMessageResourceName="LastNameRequired")]
[StringLength(160, 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
// ..
}
MVC4数据注释与验证
MVC4数据注释与验证
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var album = storeDB.Albums.Find(id);
if(TryUpdateModel(album))
{
// ...
}
}
MVC4数据注释与验证
MVC4数据注释与验证

Validation and Model State验证模型状态

ModelState.IsValid == false
ModelState.IsValidField("LastName") == false
ModelState["LastName"].Errors.Count > 0

验证失败的信息

var lastNameErrorMessage = ModelState["LastName"].Errors[0].ErrorMessage;

VIEW验证

@Html.ValidationMessageFor(m => m.LastName)

Controller Actions and Validation Errors控制器验证错误信息

MVC4数据注释与验证
MVC4数据注释与验证
[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);
}
MVC4数据注释与验证
MVC4数据注释与验证

a啊

MVC4数据注释与验证
MVC4数据注释与验证
[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);
}
MVC4数据注释与验证
MVC4数据注释与验证

CUSTOM VALIDATION LOGIC自定义验证逻辑

继承ValidationAttribute

MVC4数据注释与验证
MVC4数据注释与验证
using System.ComponentModel.DataAnnotations;
namespace MvcMusicStore.Infrastructure
{
public class MaxWordsAttribute : ValidationAttribute
{
}
}
MVC4数据注释与验证
MVC4数据注释与验证

重写 IsValid

MVC4数据注释与验证
MVC4数据注释与验证
public class MaxWordsAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
return ValidationResult.Success;
}
}
MVC4数据注释与验证
MVC4数据注释与验证

完整自定义验证代码

MVC4数据注释与验证
MVC4数据注释与验证
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;
    }

}
MVC4数据注释与验证
MVC4数据注释与验证

Model部分代码

[Required]
[StringLength(160)]
[MaxWords(10, ErrorMessage="There are too many
words in {0}")]
public string LastName { get; set; }

IValidatableObject模型中自定义验证类

MVC4数据注释与验证
MVC4数据注释与验证
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 > 10)
            {
                yield return new ValidationResult("The last name has too many words!",
                new[] { "LastName" });
            }
        }
        [Required]
        [StringLength(160)]      
        public string LastName { get; set; }
    }
}
MVC4数据注释与验证
MVC4数据注释与验证

Display

[Required]
[StringLength(160, MinimumLength=3)]
[Display(Name="First Name")]
public string FirstName { get; set; }

自动生成编辑页面

<fieldset>
<legend>Shipping Information</legend>
@Html.EditorForModel()
</fieldset>

Order控制字段顺序

MVC4数据注释与验证
MVC4数据注释与验证
[Required]
[StringLength(160)]
[Display(Name="Last Name", Order=15001)]
[MaxWords(10, ErrorMessage="There are too many words in {0}")]
public string LastName { get; set; }
[Required]
[StringLength(160, MinimumLength=3)]
[Display(Name="First Name", Order=15000)]
public string FirstName { get; set; }
MVC4数据注释与验证
MVC4数据注释与验证

隐藏属性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数据注释与验证

上一篇:WINCE 6.0 开发相关问题整理


下一篇:微软职位内部推荐-Senior SDE for Win Shell Exp