首页 > Web开发 > 详细

MVC3 Model Binding验证方式

时间:2014-04-10 23:32:11      阅读:661      评论:0      收藏:0      [点我收藏+]

 

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

bubuko.com,布布扣
[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(); 
    } 
}
bubuko.com,布布扣

2、Model元数据验证

bubuko.com,布布扣
[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; }
bubuko.com,布布扣
自定义验证,主要是实现ValidationAttribute类的IsValid方法,下面的类定义了对输入时间范围的验证

bubuko.com,布布扣
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);
        }
bubuko.com,布布扣

 

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

bubuko.com,布布扣
 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" });
            }
}
bubuko.com,布布扣

 

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">

 






MVC3 Model Binding验证方式,布布扣,bubuko.com

MVC3 Model Binding验证方式

原文:http://www.cnblogs.com/gossip/p/3656676.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!