MVC3 Model Binding验证方式

 

1、使用ModelState在Action中进行验证

[HttpPost] 
public ViewResult MakeBooking(Appointment appt) { 
    if (string.IsNullOrEmpty(appt.ClientName)) { 
        ModelState.AddModelError("ClientName", "Please enter your name"); 
    } 
    if (ModelState.IsValidField("Date") && DateTime.Now > appt.Date) { 
        ModelState.AddModelError("Date", "Please enter a date in the future"); 
    } 
    if (!appt.TermsAccepted) { 
        ModelState.AddModelError("TermsAccepted", "You must accept the terms"); 
    } 
    if (ModelState.IsValid) { 
        return View("Completed", appt); 
    } else { 
        return View(); 
    } 
}

2、Model元数据验证

[DisplayName("用户名")]
        [Required(ErrorMessage = "请输入用户名")]
        public string UserName { get; set; }

        [DisplayName("是否删除")]
        [Required]
        public int? IsDelete { get; set; }


        [DisplayName("用户状态")]
        [Required]
        public int? UserStatus { get; set; }

        [DisplayName("初始日期")]
        [Required]
        [DataType(DataType.Date)]
        [DateRange("2014-03-01", "2014-05-01")]
        public DateTime? BirthDate { get; set; }

        [DisplayName("创建日期")]
        [Required]
        [DataType(DataType.Date)]
        public DateTime? CreateTime { get; set; }
自定义验证,主要是实现ValidationAttribute类的IsValid方法,下面的类定义了对输入时间范围的验证

public class DateRangeAttribute : ValidationAttribute
    {
        private string begin;
        private string end;
        public DateRangeAttribute(string begin, string end)
        {
            this.begin = begin;
            this.end = end;
        }

        public override bool IsValid(object value)
        {
            DateTime dtBegin;
            DateTime dtEnd;
            DateTime dtValue;

            if (value == null || !DateTime.TryParse(value.ToString(), out dtValue))
            {
                ErrorMessage = "错误的输入日期格式";
                return false;
            }

            if (!DateTime.TryParse(begin.ToString(), out dtBegin))
            {
                ErrorMessage = "错误的开始日期格式";
                return false;
            }

            if (!DateTime.TryParse(end.ToString(), out dtEnd))
            {
                ErrorMessage = "错误的结束日期格式";
                return false;
            }



            if (dtValue < dtBegin || dtValue > dtEnd)
            {
                ErrorMessage = string.Format("输入日期必须大于{0}并且大于{1}", begin.ToString(), end.ToString());
                return false;
            }

            return true;
            //return base.IsValid(value);
        }

 

 
3、实现IValidatableObject接口,实现单独方法验证

 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            UserInfoViewModel userInfo = validationContext.ObjectInstance as UserInfoViewModel;

            if (null == userInfo)
            {
                yield break;
            }

            if (string.IsNullOrEmpty(userInfo.UserName))
            {
                yield return new ValidationResult("'UserName'是必需字段", new string[] { "UserName" });
            }
            if (userInfo.UserName != "123")
            {
                yield return new ValidationResult("'UserName'必须为123", new string[] { "UserName" });
            }
}

 

4、启动客户端验证
4.1 配置文件

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

     4.2 View

@Html.ValidationSummary(true)

@Html.LabelFor(m => m.BirthDate):
@Html.EditorFor(m => m.BirthDate)
@Html.ValidationMessageFor(m => m.BirthDate)

 4.3 生成的Html代码
<input class="text-box single-line input-validation-error" data-val="true" data-val-number="字段 是否删除 必须是一个数字。" data-val-required="是否删除 字段是必需的。" id="IsDelete" name="IsDelete" type="text" value="0">

 






posted @ 2014-04-10 15:48    阅读(854)  评论(0编辑  收藏  举报