在ASP.NET MVC4中自定义错误消息MVC的无效DateTime
发布时间:2020-12-16 00:37:08 所属栏目:asp.Net 来源:网络整理
导读:我无法使用我的模型中的数据注释指定验证DateTime输入值的错误消息。我真的想使用适当的DateTime验证器(而不是正则表达式等)。 [DataType(DataType.DateTime,ErrorMessage = "A valid Date or Date and Time must be entered eg. January 1,2014 12:00AM")]p
我无法使用我的模型中的数据注释指定验证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>()); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – 在代码中设置PageSize时,DataPager停止工作
- asp.net – 为什么当试图保存更改时,GridView行“null”的D
- asp.net-mvc – MVC 3中的区域全局过滤器
- asp.net-mvc – 在MVC Razor视图中使用@RenderBody有什么意
- asp.net – 反伪造cookie令牌和表单字段令牌在MVC 4中不匹配
- asp.net – 使用sql helper时出现超时问题(Microsoft.Appli
- asp.net-web-api – 如何在WebApi中获取HttpRequestMessage
- 帮助页面ASP.NET vNext MVC 6 Web Api
- 什么是Application Server for ASP.NET?
- asp.net-mvc-3 – MVC3:如何在HtmlHelper扩展中以编程方式
推荐文章
站长推荐
- ASP.NET MVC集成EntLib实现“自动化”异常处理[实
- asp.net – 什么时候应该使用Page.DataBind()和C
- asp.net-mvc – 用于对Office 365 AD进行身份验证
- ASP.NET AJAX AsyncFileUpload UploadedComplete
- asp.net – VB.NET接口
- asp.net-mvc – HttpResponseException和HttpExc
- asp.net-mvc – ASP.NET MVC Textarea HTML帮助器
- ASP.NET CodeFile,CodeBehind和Inherits
- ASP.NET MVC 3 Razor – jQuery Intellisense
- asp.net-mvc-2 – 从MCV2视图中的模型集合中读取
热点阅读