自定义错误消息MVC在ASP.NET MVC4一个无效的日期时间 [英] Customize the Error Message MVC for an invalid DateTime in ASP.NET MVC4
本文介绍了自定义错误消息MVC在ASP.NET MVC4一个无效的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有麻烦,指定使用数据标注在我的模型一个DateTime输入值的验证错误消息。我真的想使用正确的日期时间验证器(相对于正则表达式,等等)。
I am having trouble specifying the error message for the validation of a DateTime input value using data annotations in my model. I would really like to use the proper DateTime validator (as opposed to Regex, etc).
[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; }
我仍然得到默认的日期验证信息字段的日期必须是最新的。
I still get the default date validation message of "The field Date must be a date."
我缺少的东西吗?
推荐答案
我有一个肮脏的解决方案。
I have one dirty solution.
创建自定义的模型绑定:
Create custom model 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中:
And then in Global.asax.cs:
protected void Application_Start()
{
//...
ModelBinders.Binders.Add(typeof(DateTime), new CustomModelBinder<DateTime>());
这篇关于自定义错误消息MVC在ASP.NET MVC4一个无效的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文