Chr*_*cht 19 asp.net validation asp.net-mvc asp.net-mvc-4
我在使用模型中的数据注释指定验证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; }
Run Code Online (Sandbox Code Playgroud)
我仍然收到"字段日期必须是日期"的默认日期验证消息.
我错过了什么吗?
cil*_*ler 39
将以下键添加到Global.asax的Application_Start()中
ClientDataTypeModelValidatorProvider.ResourceClassKey = "YourResourceName";
DefaultModelBinder.ResourceClassKey = "YourResourceName";
Run Code Online (Sandbox Code Playgroud)
在App_GlobalResources文件夹中创建YourResourceName.resx并添加以下键
小智 14
我找到了一个简单的解决方法.
你可以保持你的模型不受影响.
[DataType(DataType.Date)]
public DateTime Date { get; set; }
Run Code Online (Sandbox Code Playgroud)
然后覆盖视图中的"data-val-date"属性.
@Html.TextBoxFor(model => model.Date, new
{
@class = "form-control",
data_val_date = "Custom error message."
})
Run Code Online (Sandbox Code Playgroud)
或者,如果要参数化消息,可以使用静态函数String.Format:
@Html.TextBoxFor(model => model.Date, new
{
@class = "form-control",
data_val_date = String.Format("The field '{0}' must be a valid date.",
Html.DisplayNameFor(model => model.Date))
})
Run Code Online (Sandbox Code Playgroud)
与资源类似:
@Html.TextBoxFor(model => model.Date, new
{
@class = "form-control",
data_val_date = String.Format(Resources.ErrorMessages.Date,
Html.DisplayNameFor(model => model.Date))
})
Run Code Online (Sandbox Code Playgroud)
我有一个脏的解决方案.
创建自定义模型绑定
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在Global.asax.cs中:
protected void Application_Start()
{
//...
ModelBinders.Binders.Add(typeof(DateTime), new CustomModelBinder<DateTime>());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25066 次 |
| 最近记录: |