我无法使用我的模型中的数据注释指定验证DateTime输入值的错误消息。我真的想使用适当的DateTime验证器(而不是正则表达式等)。
[DataType(DataType.DateTime,ErrorMessage = "A valid Date or Date and Time must be entered eg. January 1,2014 12:00AM")] public DateTime Date { get; set; }
我仍然得到默认日期验证消息“字段日期必须是日期”。
我错过了什么吗?
解决方法
我有一个脏的解决方案。
创建自定义模型binder:
public class CustomModelBinder<T> : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if(value != null && !String.IsNullOrEmpty(value.AttemptedValue)) { T temp = default(T); try { temp = ( T )TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value.AttemptedValue); } catch { bindingContext.ModelState.AddModelError(bindingContext.ModelName,"A valid Date or Date and Time must be entered eg. January 1,2014 12:00AM"); bindingContext.ModelState.SetModelValue(bindingContext.ModelName,value); } return temp; } return base.BindModel(controllerContext,bindingContext); } }
然后在Global.asax.cs中:
protected void Application_Start() { //... ModelBinders.Binders.Add(typeof(DateTime),new CustomModelBinder<DateTime>());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。