首页 > 代码库 > ASP.NET MVC 的注解
ASP.NET MVC 的注解
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace 注解的应用.Models
{
public class User
{
[HiddenInput(DisplayValue = http://www.mamicode.com/false)]
//[ScaffoldColumn(false)]
[Display(Name="编号")]
public int Id { get; set; }
[Display(Name="用户名")]
//[StringLength(10)]
//[Common.MyStringLength(10,ErrorMessage="{0}字数太多了!")]
//[Common.MyStringLength(5)]
[Common.MyStringLength(5,ErrorMessage="{0}字符太少了")]
[Required(ErrorMessage="请输入用户名")]
[Remote("CheckValid", "Home", AdditionalFields = "UserName,Pwd",ErrorMessage="该用户已存在,请重新输入")]
public string UserName { get; set; }
[DataType(DataType.Password)]
[Display(Name="密码")]
[System.ComponentModel.DataAnnotations.Compare("UserName",ErrorMessage="密码不一致")]
public string Pwd { get; set; }
[DisplayFormat(DataFormatString="{0:C}",ApplyFormatInEditMode=false)]
[Range(10,30)]
public decimal Price { get; set; }
//使用DataType(DataType.EmailAddress,ErrorMessage="请输入正确的Email地址")自定义的错误消息不会生效
//[DataType(DataType.EmailAddress,ErrorMessage="请输入正确的Email地址")]
[RegularExpression(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "请输入正确的Email地址")]
public string Email { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace 注解的应用.Common
{
/// <summary>
/// 自定义注解类,自定义注解不支持客户端验证,在模型绑定时执行IsValid方法执行验证逻辑,
/// 如果不调用FormatErrorMessage方法进行格式化,传入格式化的错误消息,则在
/// [Common.MyStringLength(10,ErrorMessage="{0}字数太多了!")]中自定义的消息不回生效
/// </summary>
public class MyStringLengthAttribute:ValidationAttribute
{
private readonly int MaxLength;
public MyStringLengthAttribute(int maxLength)
{
this.MaxLength = maxLength;
}
//protected override ValidationResult IsValid(object value, ValidationContext validationContext)
//{
// string content = value.ToString();
// if (content.Length > MaxLength)
// {
// //return new ValidationResult("输入的字符太多了!^_^");
// string errorMessage = FormatErrorMessage(validationContext.DisplayName);
// return new ValidationResult(errorMessage);
// }
// return ValidationResult.Success;
// //return base.IsValid(value, validationContext);
//}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if (value.ToString().Length < MaxLength)
{
//return new ValidationResult("请输入" + MaxLength + "位以上长度的字符!");
string errorMessage = FormatErrorMessage(validationContext.DisplayName + "请输入" + MaxLength + "位以上长度的字符!");
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
}
}
ASP.NET MVC 的注解