在ASP.NET MVC4中自定义错误消息MVC的无效DateTime
发布时间:2020-05-23 16:27:31 所属栏目:asp.Net 来源:互联网
导读:我无法使用我的模型中的数据注释指定验证DateTime输入值的错误消息。我真的想使用适当的DateTime验证器(而不是正则表达式等)。 [DataType(DataType.DateTime, ErrorMessage = A valid Date or Date and Time must be entered eg. January 1, 2014 12:00AM)]pu
|
我无法使用我的模型中的数据注释指定验证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-mvc – 您是否使用任何自定义ASP.NET MVC HtmlHelp
- ASP.NET,C#,IIS,MIME类型,文件上传条件
- asp.net-mvc-4 – ASP.NET MVC 4通过ActionLink传递对象变量
- asp.net – MSBuild:自动收集db迁移脚本?
- asp.net – 如何创建一个.ICS文件与多个VEVENT导入到现有的
- ASP.NET UserControl类库
- asp.net-mvc – 如何删除MVC网站中的所有当前域名Cookie?
- 在IIS托管的asp.net Web应用程序中打开页面时“无法找到资源
- 在ASP.NET应用程序中使用out-of-process会话状态的SQL Serv
- asp.net – 在做TDD时如何最好地创建一个测试数据库?
推荐文章
站长推荐
- .net – 如何动态清除用户控件中的所有控件?
- asp.net – 什么是system.globalization它和本地
- asp.net-mvc – 在MVC4中为ViewModel设置默认值的
- 最佳实践:ASP.NET中的CSS或主题?
- asp.net – 身份cookie在一段时间后会丢失自定义
- 增加ASP.NET站点的executionTimeout和maxRequest
- asp.net – WebForms中的Tabbing行为
- “DataSource和DataSourceID都被定义为”使用ASP
- asp.net – 基于web.config的url重写的绝对最小内
- 如果method参数是string或int,则ASP.NET WebAPI抛
热点阅读
